ngram
listlengths 0
82k
|
|---|
[
"a mapping which claims to contain all keys, each with",
"23. ''' __metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def",
"arbitrary positional args, result is 23. ''' __metaclass__ = MetaInterfaceChecker",
"you can also call an instance with arbitrary positional args,",
"def __delitem__(self, key): pass def __contains__(self, key): return True def",
"claims to contain all keys, each with a value of",
"of 23; item setting and deletion are no-ops; you can",
"call an instance with arbitrary positional args, result is 23.",
"return 23 def __setitem__(self, key, value): pass def __delitem__(self, key):",
"def __contains__(self, key): return True def __call__(self, *args): return 23",
"__contains__(self, key): return True def __call__(self, *args): return 23 sk",
"return True def __call__(self, *args): return 23 sk = Skidoo()",
"__implements__ = IMinimalMapping, ICallable def __getitem__(self, key): return 23 def",
"instance with arbitrary positional args, result is 23. ''' __metaclass__",
"MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def __getitem__(self, key): return 23",
"deletion are no-ops; you can also call an instance with",
"= MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def __getitem__(self, key): return",
"__setitem__(self, key, value): pass def __delitem__(self, key): pass def __contains__(self,",
"mapping which claims to contain all keys, each with a",
"pass def __contains__(self, key): return True def __call__(self, *args): return",
"key): return True def __call__(self, *args): return 23 sk =",
"def __getitem__(self, key): return 23 def __setitem__(self, key, value): pass",
"positional args, result is 23. ''' __metaclass__ = MetaInterfaceChecker __implements__",
"result is 23. ''' __metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping,",
"__delitem__(self, key): pass def __contains__(self, key): return True def __call__(self,",
"23 def __setitem__(self, key, value): pass def __delitem__(self, key): pass",
"also call an instance with arbitrary positional args, result is",
"is 23. ''' __metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable",
"and deletion are no-ops; you can also call an instance",
"no-ops; you can also call an instance with arbitrary positional",
"are no-ops; you can also call an instance with arbitrary",
"to contain all keys, each with a value of 23;",
"key): return 23 def __setitem__(self, key, value): pass def __delitem__(self,",
"key): pass def __contains__(self, key): return True def __call__(self, *args):",
"value): pass def __delitem__(self, key): pass def __contains__(self, key): return",
"class Skidoo(object): ''' a mapping which claims to contain all",
"IMinimalMapping, ICallable def __getitem__(self, key): return 23 def __setitem__(self, key,",
"with arbitrary positional args, result is 23. ''' __metaclass__ =",
"each with a value of 23; item setting and deletion",
"value of 23; item setting and deletion are no-ops; you",
"setting and deletion are no-ops; you can also call an",
"can also call an instance with arbitrary positional args, result",
"args, result is 23. ''' __metaclass__ = MetaInterfaceChecker __implements__ =",
"Skidoo(object): ''' a mapping which claims to contain all keys,",
"__getitem__(self, key): return 23 def __setitem__(self, key, value): pass def",
"contain all keys, each with a value of 23; item",
"key, value): pass def __delitem__(self, key): pass def __contains__(self, key):",
"pass def __delitem__(self, key): pass def __contains__(self, key): return True",
"which claims to contain all keys, each with a value",
"__metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def __getitem__(self, key):",
"a value of 23; item setting and deletion are no-ops;",
"23; item setting and deletion are no-ops; you can also",
"ICallable def __getitem__(self, key): return 23 def __setitem__(self, key, value):",
"def __setitem__(self, key, value): pass def __delitem__(self, key): pass def",
"''' __metaclass__ = MetaInterfaceChecker __implements__ = IMinimalMapping, ICallable def __getitem__(self,",
"all keys, each with a value of 23; item setting",
"''' a mapping which claims to contain all keys, each",
"= IMinimalMapping, ICallable def __getitem__(self, key): return 23 def __setitem__(self,",
"keys, each with a value of 23; item setting and",
"with a value of 23; item setting and deletion are",
"an instance with arbitrary positional args, result is 23. '''",
"item setting and deletion are no-ops; you can also call"
] |
[
"only available in Google Colab Enviroment; otherwise, it raises a",
"str: \"\"\"Mount Google Drive storage of the current Google account",
"of Google Colab.\") from google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir",
"current Google account and return the root path. Functionality only",
"RuntimeError(\"Cannot mount Google Drive outside of Google Colab.\") from google.colab",
"Google Colab Enviroment; otherwise, it raises a RuntimeError. \"\"\" if",
"Functionality only available in Google Colab Enviroment; otherwise, it raises",
"it raises a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is None): raise",
"a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot mount",
"import importlib __all__ = ['mount_gdrive'] def mount_gdrive() -> str: \"\"\"Mount",
"otherwise, it raises a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is None):",
"import drive drive.mount('/content/gdrive', force_remount=True) root_dir = \"/content/gdrive/My Drive/\" return root_dir",
"\"\"\"Mount Google Drive storage of the current Google account and",
"= ['mount_gdrive'] def mount_gdrive() -> str: \"\"\"Mount Google Drive storage",
"def mount_gdrive() -> str: \"\"\"Mount Google Drive storage of the",
"the root path. Functionality only available in Google Colab Enviroment;",
"mount_gdrive() -> str: \"\"\"Mount Google Drive storage of the current",
"available in Google Colab Enviroment; otherwise, it raises a RuntimeError.",
"Google account and return the root path. Functionality only available",
"importlib __all__ = ['mount_gdrive'] def mount_gdrive() -> str: \"\"\"Mount Google",
"\"\"\" if (importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot mount Google Drive",
"-> str: \"\"\"Mount Google Drive storage of the current Google",
"google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir = \"/content/gdrive/My Drive/\" return",
"Colab.\") from google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir = \"/content/gdrive/My",
"raises a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot",
"(importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot mount Google Drive outside of",
"and return the root path. Functionality only available in Google",
"account and return the root path. Functionality only available in",
"in Google Colab Enviroment; otherwise, it raises a RuntimeError. \"\"\"",
"Drive outside of Google Colab.\") from google.colab import drive drive.mount('/content/gdrive',",
"Google Drive outside of Google Colab.\") from google.colab import drive",
"None): raise RuntimeError(\"Cannot mount Google Drive outside of Google Colab.\")",
"raise RuntimeError(\"Cannot mount Google Drive outside of Google Colab.\") from",
"outside of Google Colab.\") from google.colab import drive drive.mount('/content/gdrive', force_remount=True)",
"if (importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot mount Google Drive outside",
"of the current Google account and return the root path.",
"the current Google account and return the root path. Functionality",
"return the root path. Functionality only available in Google Colab",
"path. Functionality only available in Google Colab Enviroment; otherwise, it",
"['mount_gdrive'] def mount_gdrive() -> str: \"\"\"Mount Google Drive storage of",
"Colab Enviroment; otherwise, it raises a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\")",
"Enviroment; otherwise, it raises a RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is",
"from google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir = \"/content/gdrive/My Drive/\"",
"storage of the current Google account and return the root",
"root path. Functionality only available in Google Colab Enviroment; otherwise,",
"mount Google Drive outside of Google Colab.\") from google.colab import",
"__all__ = ['mount_gdrive'] def mount_gdrive() -> str: \"\"\"Mount Google Drive",
"RuntimeError. \"\"\" if (importlib.util.find_spec(\"google.colab\") is None): raise RuntimeError(\"Cannot mount Google",
"Drive storage of the current Google account and return the",
"is None): raise RuntimeError(\"Cannot mount Google Drive outside of Google",
"Google Colab.\") from google.colab import drive drive.mount('/content/gdrive', force_remount=True) root_dir =",
"Google Drive storage of the current Google account and return"
] |
[
"self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def",
"taken ) with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user)",
"def _createExample(self): user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user,",
"AppointmentError, StatusRights, ) from wasch import tvkutils, payment class WashUserTestCase(TestCase):",
"= WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31, # User",
") from wasch import tvkutils, payment class WashUserTestCase(TestCase): def test_god(self):",
"class AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName = 'poor' exampleTime =",
"self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name for group in god.user.groups.all()) for",
"lastMachine = \\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True",
"user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable(",
"appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference = appointment.reference self.assertEqual(",
"exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable =",
"user = User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god()",
"as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment taken with self.assertRaises(AppointmentError)",
"self.exampleMachine, user) def test_use(self): user = User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment(",
"_ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name for",
"user=user, wasUsed=False) def test_create(self): result = self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine,",
"self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine,",
"user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference,",
"= False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self):",
"WashParameters, # not models: AppointmentError, StatusRights, ) from wasch import",
"result = self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists(",
"Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def test_bookable(self):",
"self.assertTrue(god.user.is_superuser) group_names = (group.name for group in god.user.groups.all()) for expected_group",
"group_names = (group.name for group in god.user.groups.all()) for expected_group in",
"exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine,",
"StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName =",
"self.assertEqual(ae.exception.reason, 61) # Appointment already used with self.assertRaises(AppointmentError) as ae:",
"god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11, # Unsupported time",
"# Machine out of service ) def test_make_appointment(self): user =",
"def test_god(self): god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names",
"test_create(self): result = self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName)",
"not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine,",
"import ( Appointment, WashUser, WashParameters, # not models: AppointmentError, StatusRights,",
"exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0] def",
"user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine)",
"unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user),",
"self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31, # User not active",
"self.exampleBrokenMachine, user), 21, # Machine out of service ) def",
"def test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god, _",
"of service ) def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god, _",
"# not models: AppointmentError, StatusRights, ) from wasch import tvkutils,",
"= WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name for group",
"self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine,",
"unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference)",
"= 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25))",
"= Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference = 4481037",
"with self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61) # Appointment already",
"self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable(",
"with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41)",
"result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine,",
"user) appointment.use() with self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason, 61) #",
"Appointment taken ) with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine,",
"user = User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use()",
"= Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError) as ae:",
"models: AppointmentError, StatusRights, ) from wasch import tvkutils, payment class",
"wasUsed=False) def test_create(self): result = self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine)",
"in god.user.groups.all()) for expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase):",
"11, # Unsupported time ) unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user)",
"self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user)",
"self.exampleMachine, user), 11, # Unsupported time ) unsavedTooOldAppointment = Appointment.from_reference(",
"= True # though this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable =",
"this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True)",
"Appointment taken with self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61) #",
"as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61) # Appointment already used self.assertTrue(appointment.wasUsed)",
"result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user),",
"self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName = 'poor'",
"= User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime,",
"= User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self):",
"StatusRights, ) from wasch import tvkutils, payment class WashUserTestCase(TestCase): def",
"WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference = appointment.reference",
"Unsupported time ) unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment(",
"self.exampleTooOldTime, self.exampleMachine, user), 11, # Unsupported time ) unsavedTooOldAppointment =",
"= self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time,",
"group in god.user.groups.all()) for expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names) class",
"self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11,",
"Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41, # Appointment taken ) with",
"self.exampleTime, self.exampleMachine, user) reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine,",
"self.exampleTime, self.exampleMachine, poorUser), 31, # User not active ) self.assertTrue(Appointment.manager.bookable(",
"with self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment taken",
"= Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time,",
"django.test import TestCase from django.contrib.auth.models import ( User, ) from",
"self.exampleMachine, user) reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user),",
"AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName = 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1]",
"appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment taken with self.assertRaises(AppointmentError) as ae:",
"self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self): user =",
"self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel()",
"def test_create(self): result = self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username,",
"def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god() appointment",
"already used with self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) #",
"django.utils import timezone from django.test import TestCase from django.contrib.auth.models import",
"self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with",
"Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21, # Machine out of service",
"god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name",
"self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21, # Machine out",
"self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference)",
"test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god, _ =",
"as ae: appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment already used with",
"user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def test_use(self): user",
") result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def test_bookable(self): user =",
"with self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment already",
"self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def",
"exampleMachine, exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable",
"'waschexample' examplePoorUserName = 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991,",
"ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment,",
"class WashUserTestCase(TestCase): def test_god(self): god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff)",
"payment class WashUserTestCase(TestCase): def test_god(self): god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated)",
"test_use(self): user = User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user)",
"self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21, #",
"tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True # though this",
"def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True # though this is",
"with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def test_use(self): user =",
"as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual(",
"for group in god.user.groups.all()) for expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names)",
"from wasch.models import ( Appointment, WashUser, WashParameters, # not models:",
"= timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine, lastMachine",
"# though this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save()",
") unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine,",
"= 'waschexample' examplePoorUserName = 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime =",
"self.examplePoorUserName, isActivated=False) def _createExample(self): user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime,",
"result.machine, result.user), 41, # Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time,",
"user), 11, # Unsupported time ) unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference,",
"# Appointment already used with self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason,",
"self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name for group in god.user.groups.all())",
"exampleUserName = 'waschexample' examplePoorUserName = 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime",
"# Unsupported time ) unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference,",
"User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser),",
"self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment taken with",
"import ( User, ) from wasch.models import ( Appointment, WashUser,",
"= appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41, # Appointment",
"# Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def",
"from django.utils import timezone from django.test import TestCase from django.contrib.auth.models",
"Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get())",
"import tvkutils, payment class WashUserTestCase(TestCase): def test_god(self): god, _ =",
"( User, ) from wasch.models import ( Appointment, WashUser, WashParameters,",
"WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self): user = User.objects.get(username=self.exampleUserName)",
"result.time, result.machine, result.user), 41, # Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable(",
"user), 21, # Machine out of service ) def test_make_appointment(self):",
"self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime,",
"61) # Appointment already used with self.assertRaises(AppointmentError) as ae: appointment.rebook()",
"self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41,",
"examplePoorUserName = 'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12,",
"time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self): result = self._createExample() self.assertEqual(result.time,",
"User not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime,",
"tvkutils, payment class WashUserTestCase(TestCase): def test_god(self): god, _ = WashUser.objects.get_or_create_god()",
"User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable(",
"import TestCase from django.contrib.auth.models import ( User, ) from wasch.models",
"appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError) as",
"tvkutils.setup() self.exampleMachine.isAvailable = True # though this is default self.exampleMachine.save()",
"result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41, # Appointment",
"setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True # though this is default",
"User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self): result",
"# Appointment taken ) with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime,",
"from django.contrib.auth.models import ( User, ) from wasch.models import (",
"appointment.use() with self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment",
"poorUser = User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime,",
"WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31, # User not",
"41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine,",
"machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self): result = self._createExample() self.assertEqual(result.time, self.exampleTime)",
"user = User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment(",
"self.exampleTime, self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason,",
"Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username,",
"appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41, # Appointment taken",
"Appointment already used with self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41)",
"self.assertEqual(ae.exception.reason, 41) # Appointment taken with self.assertRaises(AppointmentError) as ae: appointment.cancel()",
"Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41, # Appointment taken ) result.cancel()",
"Appointment, WashUser, WashParameters, # not models: AppointmentError, StatusRights, ) from",
") with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason,",
"not models: AppointmentError, StatusRights, ) from wasch import tvkutils, payment",
"'poor' exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference",
"= User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use() with",
"_ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31, #",
"Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError) as ae: appointment.use()",
"# Appointment taken with self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61)",
"self.exampleMachine.isAvailable = True # though this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable",
"41, # Appointment taken ) with self.assertRaises(AppointmentError) as ae: Appointment.manager.make_appointment(",
"<reponame>waschag-tvk/pywaschedv import datetime from django.utils import timezone from django.test import",
"self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment already used",
"isActivated=False) def _createExample(self): user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine,",
"self.exampleTime, self.exampleMachine, user) def test_use(self): user = User.objects.get(username=self.exampleUserName) appointment =",
"appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment already used with self.assertRaises(AppointmentError) as",
"wasch.models import ( Appointment, WashUser, WashParameters, # not models: AppointmentError,",
"def test_use(self): user = User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine,",
"self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError) as ae: appointment.use() self.assertEqual(ae.exception.reason, 61)",
"exampleTime = Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference =",
"self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11, #",
"Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def test_use(self): user = User.objects.get(username=self.exampleUserName) appointment",
"wasch import tvkutils, payment class WashUserTestCase(TestCase): def test_god(self): god, _",
"= User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine,",
"import timezone from django.test import TestCase from django.contrib.auth.models import (",
"Machine out of service ) def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName)",
"Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self): result = self._createExample()",
"import datetime from django.utils import timezone from django.test import TestCase",
"\\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True # though",
"Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11, # Unsupported time ) unsavedTooOldAppointment",
"TestCase from django.contrib.auth.models import ( User, ) from wasch.models import",
"21, # Machine out of service ) def test_make_appointment(self): user",
"self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable(",
"25)) exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0]",
"Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31, # User not active )",
"self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41, # Appointment taken )",
"god.user), 41, # Appointment taken ) with self.assertRaises(AppointmentError) as ae:",
"appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError):",
"self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable(",
"active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user))",
"self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time,",
"service ) def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god, _ =",
"= (group.name for group in god.user.groups.all()) for expected_group in StatusRights(9).groups:",
"(group.name for group in god.user.groups.all()) for expected_group in StatusRights(9).groups: self.assertIn(expected_group,",
"= \\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup() self.exampleMachine.isAvailable = True #",
") def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god()",
"Appointment.manager.scheduled_appointment_times()[-1] exampleTooOldTime = timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference = 4481037 exampleMachine,",
"12, 25)) exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine, lastMachine = \\",
"= User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god, _ = WashUser.objects.get_or_create_god() self.assertEqual(",
"self.exampleMachine, poorUser), 31, # User not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime,",
"self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine,",
"user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user),",
"god, _ = WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user)",
"group_names) class AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName = 'poor' exampleTime",
"= Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable(",
"isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self): user = User.objects.get(username=self.exampleUserName) return",
"self.exampleMachine, god.user), 41, # Appointment taken ) with self.assertRaises(AppointmentError) as",
"user) reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41,",
"appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user))",
"Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment(",
"expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName = 'waschexample'",
"self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable(",
"self.exampleTime, self.exampleMachine, god.user), 41, # Appointment taken ) with self.assertRaises(AppointmentError)",
"out of service ) def test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god,",
"User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine,",
"self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11, # Unsupported",
"_ = WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference",
"test_make_appointment(self): user = User.objects.get(username=self.exampleUserName) god, _ = WashUser.objects.get_or_create_god() appointment =",
"41, # Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user))",
"self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual(",
"= WashUser.objects.get_or_create_god() appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference =",
"time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName)",
"self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime,",
"from django.test import TestCase from django.contrib.auth.models import ( User, )",
"self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser",
"reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41, #",
"self._createExample() self.assertEqual(result.time, self.exampleTime) self.assertEqual(result.machine, self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine))",
"result.user), 41, # Appointment taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine,",
"though this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName,",
"result.machine, result.user)) def test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName)",
"unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21, # Machine",
"self.exampleMachine) self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user))",
"taken with self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61) # Appointment",
"timezone.make_aware(datetime.datetime(1991, 12, 25)) exampleTooOldReference = 4481037 exampleMachine, exampleBrokenMachine, lastMachine =",
"taken ) result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def test_bookable(self): user",
"Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) reference = appointment.reference self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime,",
"Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime, machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime)",
"WashUser, WashParameters, # not models: AppointmentError, StatusRights, ) from wasch",
"return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def test_create(self): result =",
"self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time,",
"self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason, 61) # Appointment already used",
"self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine,",
"self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, god.user), 41, # Appointment taken )",
"WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self): user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create(",
"True # though this is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False",
"test_god(self): god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names =",
") self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual(",
"in StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName = 'waschexample' examplePoorUserName",
"self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method', 'empty')",
"WashParameters.objects.update_value('bonus-method', 'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime,",
"from wasch import tvkutils, payment class WashUserTestCase(TestCase): def test_god(self): god,",
"self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, god.user)) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime,",
"WashUserTestCase(TestCase): def test_god(self): god, _ = WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser)",
"result.time, result.machine, result.user)) def test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser =",
"self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21,",
"poorUser), 31, # User not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine,",
"is default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser(",
"31, # User not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user))",
"machine=self.exampleMachine, user=user).reference) self.assertEqual(unsavedTooOldAppointment.time, self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual(",
"ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment taken with self.assertRaises(AppointmentError) as",
"result.time, result.machine, result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41, #",
"False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False) def _createExample(self): user",
"user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False) def",
"result.cancel() self.assertTrue(Appointment.manager.bookable( result.time, result.machine, result.user)) def test_bookable(self): user = User.objects.get(username=self.exampleUserName)",
"_createExample(self): user = User.objects.get(username=self.exampleUserName) return Appointment.objects.create( time=self.exampleTime, machine=self.exampleMachine, user=user, wasUsed=False)",
"self.exampleTime, self.exampleMachine, user) self.assertEqual(ae.exception.reason, 41) appointment.cancel() self.assertEqual( appointment, Appointment.manager.filter_for_reference(reference).get()) WashParameters.objects.update_value('bonus-method',",
"self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def test_use(self): user = User.objects.get(username=self.exampleUserName)",
"user) def test_use(self): user = User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime,",
"time ) unsavedTooOldAppointment = Appointment.from_reference( self.exampleTooOldReference, user) self.assertEqual(self.exampleTooOldReference, Appointment( time=self.exampleTooOldTime,",
"result.user)) def test_bookable(self): user = User.objects.get(username=self.exampleUserName) poorUser = User.objects.get(username=self.examplePoorUserName) god,",
"# User not active ) self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) self.assertTrue(Appointment.manager.bookable(",
"timezone from django.test import TestCase from django.contrib.auth.models import ( User,",
"result.user)) self.assertEqual( Appointment.manager.why_not_bookable( result.time, result.machine, result.user), 41, # Appointment taken",
"self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName, isActivated=False)",
"god.user.groups.all()) for expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName",
"self.exampleTime, self.exampleBrokenMachine, user), 21, # Machine out of service )",
"self.assertEqual(result.user.username, self.exampleUserName) self.assertTrue(Appointment.manager.appointment_exists( result.time, result.machine)) self.assertFalse(Appointment.manager.bookable( result.time, result.machine, result.user)) self.assertEqual(",
"self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) def test_use(self):",
"User, ) from wasch.models import ( Appointment, WashUser, WashParameters, #",
"= 4481037 exampleMachine, exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0] def setUp(self):",
"datetime from django.utils import timezone from django.test import TestCase from",
") from wasch.models import ( Appointment, WashUser, WashParameters, # not",
"self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTooOldTime, self.exampleMachine, user), 11, # Unsupported time )",
"User.objects.get(username=self.exampleUserName) appointment = Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine, user) appointment.use() with self.assertRaises(AppointmentError)",
"41) # Appointment taken with self.assertRaises(AppointmentError) as ae: appointment.cancel() self.assertEqual(ae.exception.reason,",
"( Appointment, WashUser, WashParameters, # not models: AppointmentError, StatusRights, )",
"django.contrib.auth.models import ( User, ) from wasch.models import ( Appointment,",
"used with self.assertRaises(AppointmentError) as ae: appointment.rebook() self.assertEqual(ae.exception.reason, 41) # Appointment",
"self.exampleTooOldTime) self.assertEqual(unsavedTooOldAppointment.machine, self.exampleMachine) self.assertEqual( unsavedTooOldAppointment.user.username, self.exampleUserName) self.assertEqual( unsavedTooOldAppointment.reference, self.exampleTooOldReference) self.assertEqual(",
"default self.exampleMachine.save() self.exampleBrokenMachine.isAvailable = False self.exampleMachine.save() WashUser.objects.create_enduser(self.exampleUserName, isActivated=True) WashUser.objects.create_enduser( self.examplePoorUserName,",
"'empty') self.assertTrue(Appointment.manager.bookable( self.exampleTime, self.exampleMachine, user)) with self.assertRaises(payment.PaymentError): Appointment.manager.make_appointment( self.exampleTime, self.exampleMachine,",
"god, _ = WashUser.objects.get_or_create_god() self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleMachine, poorUser), 31,",
"WashUser.objects.get_or_create_god() self.assertTrue(god.isActivated) self.assertTrue(god.user.is_staff) self.assertTrue(god.user.is_superuser) group_names = (group.name for group in",
"4481037 exampleMachine, exampleBrokenMachine, lastMachine = \\ tvkutils.get_or_create_machines()[0] def setUp(self): tvkutils.setup()",
"ae: appointment.use() self.assertEqual(ae.exception.reason, 61) # Appointment already used with self.assertRaises(AppointmentError)",
"self.assertEqual( Appointment.manager.why_not_bookable( self.exampleTime, self.exampleBrokenMachine, user), 21, # Machine out of",
"for expected_group in StatusRights(9).groups: self.assertIn(expected_group, group_names) class AppointmentTestCase(TestCase): exampleUserName ="
] |
[
"nums[q] < target: return False elif nums[q] > target: q",
"List[int], target: int) -> bool: # ans = 0 #",
"p < q: if nums[p] > target: return False elif",
"def isMajorityElement(self, nums: List[int], target: int) -> bool: # d",
"-> bool: # d = Counter(nums) # return d[target] >",
"nums: return False if len(nums) == 1: return nums[0] ==",
"len(nums)-1 while p < q: if nums[p] > target: return",
"0, len(nums)-1 while p < q: if nums[p] > target:",
"# return ans > len(target)//2 class Solution: def isMajorityElement(self, nums:",
"# for num in nums: # if num == target:",
"target: int) -> bool: # d = Counter(nums) # return",
"isMajorityElement(self, nums: List[int], target: int) -> bool: if not nums:",
"List[int], target: int) -> bool: if not nums: return False",
"+= 1 if nums[q] < target: return False elif nums[q]",
"if not nums: return False if len(nums) == 1: return",
"> target: q -= 1 if nums[p] == nums[q] ==",
"target: return False elif nums[q] > target: q -= 1",
"# class Solution: # def isMajorityElement(self, nums: List[int], target: int)",
"nums[p] < target: p += 1 if nums[q] < target:",
"Solution: # def isMajorityElement(self, nums: List[int], target: int) -> bool:",
"bool: # ans = 0 # for num in nums:",
"# return d[target] > len(nums)//2 # class Solution: # def",
"elif nums[q] > target: q -= 1 if nums[p] ==",
"len(target)//2 class Solution: def isMajorityElement(self, nums: List[int], target: int) ->",
"target: int) -> bool: # ans = 0 # for",
"from typing import List from collections import Counter # class",
"q: if nums[p] > target: return False elif nums[p] <",
"Counter(nums) # return d[target] > len(nums)//2 # class Solution: #",
"> len(nums)//2 # class Solution: # def isMajorityElement(self, nums: List[int],",
"in nums: # if num == target: # ans +=",
"nums: # if num == target: # ans += 1",
"1 if nums[p] == nums[q] == target: return q -",
"target: p += 1 if nums[q] < target: return False",
"class Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool:",
"return False elif nums[q] > target: q -= 1 if",
"1: return nums[0] == target p, q = 0, len(nums)-1",
"= 0 # for num in nums: # if num",
"False if len(nums) == 1: return nums[0] == target p,",
"1 if nums[q] < target: return False elif nums[q] >",
"nums: List[int], target: int) -> bool: # d = Counter(nums)",
"def isMajorityElement(self, nums: List[int], target: int) -> bool: if not",
"< target: p += 1 if nums[q] < target: return",
"target p, q = 0, len(nums)-1 while p < q:",
"typing import List from collections import Counter # class Solution:",
"-> bool: # ans = 0 # for num in",
"int) -> bool: if not nums: return False if len(nums)",
"-= 1 if nums[p] == nums[q] == target: return q",
"ans += 1 # return ans > len(target)//2 class Solution:",
"len(nums) == 1: return nums[0] == target p, q =",
"if nums[q] < target: return False elif nums[q] > target:",
"List[int], target: int) -> bool: # d = Counter(nums) #",
"Solution: def isMajorityElement(self, nums: List[int], target: int) -> bool: if",
"int) -> bool: # ans = 0 # for num",
"+= 1 # return ans > len(target)//2 class Solution: def",
"nums: List[int], target: int) -> bool: if not nums: return",
"not nums: return False if len(nums) == 1: return nums[0]",
"return False elif nums[p] < target: p += 1 if",
"# def isMajorityElement(self, nums: List[int], target: int) -> bool: #",
"# ans = 0 # for num in nums: #",
"> target: return False elif nums[p] < target: p +=",
"int) -> bool: # d = Counter(nums) # return d[target]",
"== target: # ans += 1 # return ans >",
"# d = Counter(nums) # return d[target] > len(nums)//2 #",
"d = Counter(nums) # return d[target] > len(nums)//2 # class",
"List from collections import Counter # class Solution: # def",
"return nums[0] == target p, q = 0, len(nums)-1 while",
"Counter # class Solution: # def isMajorityElement(self, nums: List[int], target:",
"# ans += 1 # return ans > len(target)//2 class",
"== 1: return nums[0] == target p, q = 0,",
"q = 0, len(nums)-1 while p < q: if nums[p]",
"target: # ans += 1 # return ans > len(target)//2",
"return False if len(nums) == 1: return nums[0] == target",
"if num == target: # ans += 1 # return",
"if len(nums) == 1: return nums[0] == target p, q",
"-> bool: if not nums: return False if len(nums) ==",
"def isMajorityElement(self, nums: List[int], target: int) -> bool: # ans",
"if nums[p] > target: return False elif nums[p] < target:",
"== target: return q - p + 1 > len(nums)//2",
"nums: List[int], target: int) -> bool: # ans = 0",
"if nums[p] == nums[q] == target: return q - p",
"isMajorityElement(self, nums: List[int], target: int) -> bool: # ans =",
"False elif nums[p] < target: p += 1 if nums[q]",
"= 0, len(nums)-1 while p < q: if nums[p] >",
"bool: if not nums: return False if len(nums) == 1:",
"nums[q] == target: return q - p + 1 >",
"1 # return ans > len(target)//2 class Solution: def isMajorityElement(self,",
"p, q = 0, len(nums)-1 while p < q: if",
"return d[target] > len(nums)//2 # class Solution: # def isMajorityElement(self,",
"import Counter # class Solution: # def isMajorityElement(self, nums: List[int],",
"target: return False elif nums[p] < target: p += 1",
"elif nums[p] < target: p += 1 if nums[q] <",
"target: q -= 1 if nums[p] == nums[q] == target:",
"while p < q: if nums[p] > target: return False",
"from collections import Counter # class Solution: # def isMajorityElement(self,",
"= Counter(nums) # return d[target] > len(nums)//2 # class Solution:",
"num == target: # ans += 1 # return ans",
"== target p, q = 0, len(nums)-1 while p <",
"d[target] > len(nums)//2 # class Solution: # def isMajorityElement(self, nums:",
"< q: if nums[p] > target: return False elif nums[p]",
"> len(target)//2 class Solution: def isMajorityElement(self, nums: List[int], target: int)",
"collections import Counter # class Solution: # def isMajorityElement(self, nums:",
"isMajorityElement(self, nums: List[int], target: int) -> bool: # d =",
"False elif nums[q] > target: q -= 1 if nums[p]",
"ans = 0 # for num in nums: # if",
"return ans > len(target)//2 class Solution: def isMajorityElement(self, nums: List[int],",
"len(nums)//2 # class Solution: # def isMajorityElement(self, nums: List[int], target:",
"ans > len(target)//2 class Solution: def isMajorityElement(self, nums: List[int], target:",
"# if num == target: # ans += 1 #",
"bool: # d = Counter(nums) # return d[target] > len(nums)//2",
"class Solution: # def isMajorityElement(self, nums: List[int], target: int) ->",
"nums[0] == target p, q = 0, len(nums)-1 while p",
"== nums[q] == target: return q - p + 1",
"nums[q] > target: q -= 1 if nums[p] == nums[q]",
"target: int) -> bool: if not nums: return False if",
"num in nums: # if num == target: # ans",
"0 # for num in nums: # if num ==",
"< target: return False elif nums[q] > target: q -=",
"for num in nums: # if num == target: #",
"q -= 1 if nums[p] == nums[q] == target: return",
"p += 1 if nums[q] < target: return False elif",
"nums[p] > target: return False elif nums[p] < target: p",
"import List from collections import Counter # class Solution: #",
"nums[p] == nums[q] == target: return q - p +"
] |
[
"= 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path:",
"of Code 2021 - Day 17 https://adventofcode.com/2021/day/17 \"\"\" import re",
"= ceil(sqrt(x1 * 8 + 1) / 2 - 1",
"arcing_good_shots = [] for x in range(x_min, x_max): for y",
"y_position >= y1: if x_position >= x1 and y_position <=",
"math import ceil, sqrt from typing import List, Tuple DAY",
"y_max = y1 * -1 arcing_good_shots = [] for x",
"re.match(regex, infile.readline()).groups()] return x1, x2, y1, y2 def maximum_altitude(y: int)",
"== '__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer =",
"str) -> int: target_area = load_data(infile_path) return count_good_shots(*target_area) if __name__",
"shot_good(x, y, x1, x2, y1, y2): arcing_good_shots.append((x, y)) direct_shot_count =",
"int, x2: int, y1: int, y2: int) -> int: x_min",
"= y1 * -1 arcing_good_shots = [] for x in",
"if x_velocity < 0 else 0 y_velocity -= 1 return",
"i in re.match(regex, infile.readline()).groups()] return x1, x2, y1, y2 def",
"x2: int, y1: int, y2: int) -> int: x_min =",
"x_velocity < 0 else 0 y_velocity -= 1 return False",
"__name__ == '__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer",
"'__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer = part_2(FULL_INPUT_FILE)",
"for y in range(y_min, y_max): if shot_good(x, y, x1, x2,",
"if shot_good(x, y, x1, x2, y1, y2): arcing_good_shots.append((x, y)) direct_shot_count",
"x1) * (y2 + 1 - y1) return len(arcing_good_shots) +",
"y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii') as infile: x1, x2, y1,",
"x1, x2, y1, y2 def maximum_altitude(y: int) -> int: return",
"from typing import List, Tuple DAY = 17 FULL_INPUT_FILE =",
"= [int(i) for i in re.match(regex, infile.readline()).groups()] return x1, x2,",
"0 else -1 if x_velocity < 0 else 0 y_velocity",
"typing import List, Tuple DAY = 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt'",
"return True x_position += x_velocity y_position += y_velocity x_velocity -=",
"int) -> int: x_min = ceil(sqrt(x1 * 8 + 1)",
"str) -> Tuple[int, int, int, int]: regex = r'target area:",
"int(y * -1 * (y * -1 - 1) /",
"Code 2021 - Day 17 https://adventofcode.com/2021/day/17 \"\"\" import re from",
"x2 and y_position >= y1: if x_position >= x1 and",
"-= 1 if x_velocity > 0 else -1 if x_velocity",
"- 1 / 2) x_max = round(x2 / 2) +",
"17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str)",
"f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) -> Tuple[int, int, int, int]: regex",
"load_data(infile_path: str) -> Tuple[int, int, int, int]: regex = r'target",
"-1 - 1) / 2) def shot_good(x_velocity: int, y_velocity: int,",
"List, Tuple DAY = 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE =",
"int, y1: int, y2: int) -> int: x_min = ceil(sqrt(x1",
"load_data(infile_path) return count_good_shots(*target_area) if __name__ == '__main__': part1_answer = part_1(FULL_INPUT_FILE)",
"for i in re.match(regex, infile.readline()).groups()] return x1, x2, y1, y2",
"int, x2: int, y1: int, y2: int) -> bool: x_position",
"- Day 17 https://adventofcode.com/2021/day/17 \"\"\" import re from math import",
"FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) ->",
"y)) direct_shot_count = (x2 + 1 - x1) * (y2",
"count_good_shots(*target_area) if __name__ == '__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1:",
"int, y1: int, y2: int) -> bool: x_position = y_position",
"= y_position = 0 while x_position <= x2 and y_position",
"[int(i) for i in re.match(regex, infile.readline()).groups()] return x1, x2, y1,",
"y1 y_max = y1 * -1 arcing_good_shots = [] for",
"int) -> int: return int(y * -1 * (y *",
"1 - x1) * (y2 + 1 - y1) return",
"+ 1 - y1) return len(arcing_good_shots) + direct_shot_count def part_1(infile_path:",
"-= 1 return False def count_good_shots(x1: int, x2: int, y1:",
"if __name__ == '__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}')",
"-> Tuple[int, int, int, int]: regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*),",
"x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii') as infile: x1, x2,",
"/ 2) def shot_good(x_velocity: int, y_velocity: int, x1: int, x2:",
"y1: int, y2: int) -> bool: x_position = y_position =",
"1) / 2 - 1 / 2) x_max = round(x2",
"y1 * -1 arcing_good_shots = [] for x in range(x_min,",
"from math import ceil, sqrt from typing import List, Tuple",
"x1: int, x2: int, y1: int, y2: int) -> bool:",
"False def count_good_shots(x1: int, x2: int, y1: int, y2: int)",
"int: return int(y * -1 * (y * -1 -",
"int, y2: int) -> int: x_min = ceil(sqrt(x1 * 8",
"part_2(infile_path: str) -> int: target_area = load_data(infile_path) return count_good_shots(*target_area) if",
"str) -> int: target_area = load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path:",
"int, x1: int, x2: int, y1: int, y2: int) ->",
"open(infile_path, 'r', encoding='ascii') as infile: x1, x2, y1, y2 =",
"* 8 + 1) / 2 - 1 / 2)",
"* -1 * (y * -1 - 1) / 2)",
">= y1: if x_position >= x1 and y_position <= y2:",
"(y * -1 - 1) / 2) def shot_good(x_velocity: int,",
"= load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path: str) -> int: target_area",
"bool: x_position = y_position = 0 while x_position <= x2",
"re from math import ceil, sqrt from typing import List,",
"return count_good_shots(*target_area) if __name__ == '__main__': part1_answer = part_1(FULL_INPUT_FILE) print(f'Part",
"'r', encoding='ascii') as infile: x1, x2, y1, y2 = [int(i)",
"x1, x2, y1, y2 = [int(i) for i in re.match(regex,",
"maximum_altitude(y: int) -> int: return int(y * -1 * (y",
"1 return False def count_good_shots(x1: int, x2: int, y1: int,",
"> 0 else -1 if x_velocity < 0 else 0",
"x_max = round(x2 / 2) + 1 y_min = y1",
"<reponame>arcadecoffee/advent-2021<filename>day17/module.py \"\"\" Advent of Code 2021 - Day 17 https://adventofcode.com/2021/day/17",
"target_area = load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path: str) -> int:",
"int]: regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r',",
"sqrt from typing import List, Tuple DAY = 17 FULL_INPUT_FILE",
"len(arcing_good_shots) + direct_shot_count def part_1(infile_path: str) -> int: target_area =",
"+= x_velocity y_position += y_velocity x_velocity -= 1 if x_velocity",
"for x in range(x_min, x_max): for y in range(y_min, y_max):",
"< 0 else 0 y_velocity -= 1 return False def",
"+ 1 y_min = y1 y_max = y1 * -1",
"x_velocity > 0 else -1 if x_velocity < 0 else",
"y1, y2 = [int(i) for i in re.match(regex, infile.readline()).groups()] return",
"DAY = 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def",
"part_1(infile_path: str) -> int: target_area = load_data(infile_path) return maximum_altitude(target_area[2]) def",
"target_area = load_data(infile_path) return count_good_shots(*target_area) if __name__ == '__main__': part1_answer",
"return len(arcing_good_shots) + direct_shot_count def part_1(infile_path: str) -> int: target_area",
"-> bool: x_position = y_position = 0 while x_position <=",
"<= y2: return True x_position += x_velocity y_position += y_velocity",
"ceil(sqrt(x1 * 8 + 1) / 2 - 1 /",
"Day 17 https://adventofcode.com/2021/day/17 \"\"\" import re from math import ceil,",
"in range(x_min, x_max): for y in range(y_min, y_max): if shot_good(x,",
"y2 def maximum_altitude(y: int) -> int: return int(y * -1",
"if x_velocity > 0 else -1 if x_velocity < 0",
"1 - y1) return len(arcing_good_shots) + direct_shot_count def part_1(infile_path: str)",
"return False def count_good_shots(x1: int, x2: int, y1: int, y2:",
"y2 = [int(i) for i in re.match(regex, infile.readline()).groups()] return x1,",
"y_position = 0 while x_position <= x2 and y_position >=",
"/ 2) x_max = round(x2 / 2) + 1 y_min",
"= y1 y_max = y1 * -1 arcing_good_shots = []",
"- x1) * (y2 + 1 - y1) return len(arcing_good_shots)",
"x_position <= x2 and y_position >= y1: if x_position >=",
"1 / 2) x_max = round(x2 / 2) + 1",
"0 else 0 y_velocity -= 1 return False def count_good_shots(x1:",
"else 0 y_velocity -= 1 return False def count_good_shots(x1: int,",
"part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer = part_2(FULL_INPUT_FILE) print(f'Part 2: {part2_answer}')",
"return x1, x2, y1, y2 def maximum_altitude(y: int) -> int:",
"Advent of Code 2021 - Day 17 https://adventofcode.com/2021/day/17 \"\"\" import",
"* (y * -1 - 1) / 2) def shot_good(x_velocity:",
"/ 2 - 1 / 2) x_max = round(x2 /",
"import re from math import ceil, sqrt from typing import",
"y2: int) -> int: x_min = ceil(sqrt(x1 * 8 +",
"[] for x in range(x_min, x_max): for y in range(y_min,",
"def part_1(infile_path: str) -> int: target_area = load_data(infile_path) return maximum_altitude(target_area[2])",
"direct_shot_count = (x2 + 1 - x1) * (y2 +",
"-> int: target_area = load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path: str)",
"y_velocity -= 1 return False def count_good_shots(x1: int, x2: int,",
"* -1 arcing_good_shots = [] for x in range(x_min, x_max):",
"maximum_altitude(target_area[2]) def part_2(infile_path: str) -> int: target_area = load_data(infile_path) return",
"y_min = y1 y_max = y1 * -1 arcing_good_shots =",
"shot_good(x_velocity: int, y_velocity: int, x1: int, x2: int, y1: int,",
"= (x2 + 1 - x1) * (y2 + 1",
"y_velocity: int, x1: int, x2: int, y1: int, y2: int)",
"def part_2(infile_path: str) -> int: target_area = load_data(infile_path) return count_good_shots(*target_area)",
"= f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) -> Tuple[int, int, int, int]:",
"return int(y * -1 * (y * -1 - 1)",
"y2: return True x_position += x_velocity y_position += y_velocity x_velocity",
"8 + 1) / 2 - 1 / 2) x_max",
"y_max): if shot_good(x, y, x1, x2, y1, y2): arcing_good_shots.append((x, y))",
"r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii') as infile:",
"else -1 if x_velocity < 0 else 0 y_velocity -=",
"-> int: return int(y * -1 * (y * -1",
"\"\"\" import re from math import ceil, sqrt from typing",
"y1, y2): arcing_good_shots.append((x, y)) direct_shot_count = (x2 + 1 -",
"y2: int) -> bool: x_position = y_position = 0 while",
"def shot_good(x_velocity: int, y_velocity: int, x1: int, x2: int, y1:",
"int, y2: int) -> bool: x_position = y_position = 0",
"https://adventofcode.com/2021/day/17 \"\"\" import re from math import ceil, sqrt from",
"f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) -> Tuple[int, int,",
"return maximum_altitude(target_area[2]) def part_2(infile_path: str) -> int: target_area = load_data(infile_path)",
"x2, y1, y2): arcing_good_shots.append((x, y)) direct_shot_count = (x2 + 1",
"x_velocity y_position += y_velocity x_velocity -= 1 if x_velocity >",
"= part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer = part_2(FULL_INPUT_FILE) print(f'Part 2:",
"2) + 1 y_min = y1 y_max = y1 *",
"ceil, sqrt from typing import List, Tuple DAY = 17",
"- y1) return len(arcing_good_shots) + direct_shot_count def part_1(infile_path: str) ->",
"- 1) / 2) def shot_good(x_velocity: int, y_velocity: int, x1:",
"* -1 - 1) / 2) def shot_good(x_velocity: int, y_velocity:",
"int, y_velocity: int, x1: int, x2: int, y1: int, y2:",
"= 0 while x_position <= x2 and y_position >= y1:",
"-> int: target_area = load_data(infile_path) return count_good_shots(*target_area) if __name__ ==",
"int, int, int]: regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with",
"x2, y1, y2 def maximum_altitude(y: int) -> int: return int(y",
"1 y_min = y1 y_max = y1 * -1 arcing_good_shots",
"x_velocity -= 1 if x_velocity > 0 else -1 if",
"int: x_min = ceil(sqrt(x1 * 8 + 1) / 2",
"-1 * (y * -1 - 1) / 2) def",
"range(x_min, x_max): for y in range(y_min, y_max): if shot_good(x, y,",
"= load_data(infile_path) return count_good_shots(*target_area) if __name__ == '__main__': part1_answer =",
"y, x1, x2, y1, y2): arcing_good_shots.append((x, y)) direct_shot_count = (x2",
"+ 1 - x1) * (y2 + 1 - y1)",
"2021 - Day 17 https://adventofcode.com/2021/day/17 \"\"\" import re from math",
"def count_good_shots(x1: int, x2: int, y1: int, y2: int) ->",
"in re.match(regex, infile.readline()).groups()] return x1, x2, y1, y2 def maximum_altitude(y:",
"while x_position <= x2 and y_position >= y1: if x_position",
"area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii') as infile: x1,",
"0 y_velocity -= 1 return False def count_good_shots(x1: int, x2:",
"with open(infile_path, 'r', encoding='ascii') as infile: x1, x2, y1, y2",
"x in range(x_min, x_max): for y in range(y_min, y_max): if",
"y1: int, y2: int) -> int: x_min = ceil(sqrt(x1 *",
"direct_shot_count def part_1(infile_path: str) -> int: target_area = load_data(infile_path) return",
"infile.readline()).groups()] return x1, x2, y1, y2 def maximum_altitude(y: int) ->",
"infile: x1, x2, y1, y2 = [int(i) for i in",
"(x2 + 1 - x1) * (y2 + 1 -",
"x1 and y_position <= y2: return True x_position += x_velocity",
"int: target_area = load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path: str) ->",
"y1, y2 def maximum_altitude(y: int) -> int: return int(y *",
"int) -> bool: x_position = y_position = 0 while x_position",
"* (y2 + 1 - y1) return len(arcing_good_shots) + direct_shot_count",
"+= y_velocity x_velocity -= 1 if x_velocity > 0 else",
"= r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii') as",
"y_position += y_velocity x_velocity -= 1 if x_velocity > 0",
"Tuple[int, int, int, int]: regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)'",
"x_max): for y in range(y_min, y_max): if shot_good(x, y, x1,",
"encoding='ascii') as infile: x1, x2, y1, y2 = [int(i) for",
"+ direct_shot_count def part_1(infile_path: str) -> int: target_area = load_data(infile_path)",
"and y_position <= y2: return True x_position += x_velocity y_position",
"x_min = ceil(sqrt(x1 * 8 + 1) / 2 -",
"1) / 2) def shot_good(x_velocity: int, y_velocity: int, x1: int,",
"range(y_min, y_max): if shot_good(x, y, x1, x2, y1, y2): arcing_good_shots.append((x,",
"x2: int, y1: int, y2: int) -> bool: x_position =",
"arcing_good_shots.append((x, y)) direct_shot_count = (x2 + 1 - x1) *",
"2) x_max = round(x2 / 2) + 1 y_min =",
">= x1 and y_position <= y2: return True x_position +=",
"(y2 + 1 - y1) return len(arcing_good_shots) + direct_shot_count def",
"def load_data(infile_path: str) -> Tuple[int, int, int, int]: regex =",
"int, int]: regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path,",
"round(x2 / 2) + 1 y_min = y1 y_max =",
"2 - 1 / 2) x_max = round(x2 / 2)",
"= [] for x in range(x_min, x_max): for y in",
"and y_position >= y1: if x_position >= x1 and y_position",
"x1, x2, y1, y2): arcing_good_shots.append((x, y)) direct_shot_count = (x2 +",
"import List, Tuple DAY = 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE",
"= f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) -> Tuple[int,",
"\"\"\" Advent of Code 2021 - Day 17 https://adventofcode.com/2021/day/17 \"\"\"",
"count_good_shots(x1: int, x2: int, y1: int, y2: int) -> int:",
"-1 if x_velocity < 0 else 0 y_velocity -= 1",
"as infile: x1, x2, y1, y2 = [int(i) for i",
"0 while x_position <= x2 and y_position >= y1: if",
"<= x2 and y_position >= y1: if x_position >= x1",
"regex = r'target area: x=(-?\\d*)\\.\\.(-?\\d*), y=(-?\\d*)\\.\\.(-?\\d*)' with open(infile_path, 'r', encoding='ascii')",
"x2, y1, y2 = [int(i) for i in re.match(regex, infile.readline()).groups()]",
"x_position += x_velocity y_position += y_velocity x_velocity -= 1 if",
"load_data(infile_path) return maximum_altitude(target_area[2]) def part_2(infile_path: str) -> int: target_area =",
"-1 arcing_good_shots = [] for x in range(x_min, x_max): for",
"def maximum_altitude(y: int) -> int: return int(y * -1 *",
"y_position <= y2: return True x_position += x_velocity y_position +=",
"in range(y_min, y_max): if shot_good(x, y, x1, x2, y1, y2):",
"int: target_area = load_data(infile_path) return count_good_shots(*target_area) if __name__ == '__main__':",
"2) def shot_good(x_velocity: int, y_velocity: int, x1: int, x2: int,",
"y2): arcing_good_shots.append((x, y)) direct_shot_count = (x2 + 1 - x1)",
"if x_position >= x1 and y_position <= y2: return True",
"+ 1) / 2 - 1 / 2) x_max =",
"x_position = y_position = 0 while x_position <= x2 and",
"TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt' def load_data(infile_path: str) -> Tuple[int, int, int,",
"y1: if x_position >= x1 and y_position <= y2: return",
"y in range(y_min, y_max): if shot_good(x, y, x1, x2, y1,",
"x_position >= x1 and y_position <= y2: return True x_position",
"Tuple DAY = 17 FULL_INPUT_FILE = f'../inputs/day{DAY:02d}/input.full.txt' TEST_INPUT_FILE = f'../inputs/day{DAY:02d}/input.test.txt'",
"y_velocity x_velocity -= 1 if x_velocity > 0 else -1",
"True x_position += x_velocity y_position += y_velocity x_velocity -= 1",
"part1_answer = part_1(FULL_INPUT_FILE) print(f'Part 1: {part1_answer}') part2_answer = part_2(FULL_INPUT_FILE) print(f'Part",
"= round(x2 / 2) + 1 y_min = y1 y_max",
"y1) return len(arcing_good_shots) + direct_shot_count def part_1(infile_path: str) -> int:",
"import ceil, sqrt from typing import List, Tuple DAY =",
"/ 2) + 1 y_min = y1 y_max = y1",
"-> int: x_min = ceil(sqrt(x1 * 8 + 1) /",
"1 if x_velocity > 0 else -1 if x_velocity <",
"17 https://adventofcode.com/2021/day/17 \"\"\" import re from math import ceil, sqrt"
] |
[
"program.rules: if rule.is_fact(): rules.append(rule) else: beta = None for lit",
"_notify(self, ground_1: List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'): subs",
"Optional['Substitutions']: for var in set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]: return",
"= [*ground_1, *ground_2] payload = (ground, subs) if payload not",
"subs is not None: payload = ([ground], subs) if payload",
"is self.parent_2: for ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1, ground,",
"self._notify(ground_1, subs_1, ground, subs) @staticmethod def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions')",
"if fact not in self.agenda: # self.agenda.append(fact) rule = Rule(lit,",
"Tuple[List['Literal'], 'Substitutions'] class Root: def __init__(self): self.children = set() def",
"subs) @staticmethod def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']: for",
"= self.rule.head.substitutes(subs) # if self.rule.type is RuleType.STRICT: # fact =",
"agenda parent.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa,",
"in self.agenda: # self.agenda.append(fact) rule = Rule(lit, self.rule.type, ground) if",
"'Beta']): if parent is self.parent_1: for ground_2, subs_2 in self.parent_2.memory:",
"self.agenda = agenda parent.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions',",
"self.memory: self.memory.append(payload) for child in self.children: child.notify([ground], subs, self) class",
"agenda: List): self.parent = parent self.rule = rule self.name =",
"self) class Beta: def __init__(self, parent_1: Union[Alfa, 'Beta'], parent_2: Alfa):",
"parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa,",
"= self.pattern.unifies(ground) if subs is not None: payload = ([ground],",
"is not None: ground = [*ground_1, *ground_2] payload = (ground,",
"not in self.memory: self.memory.append(payload) for child in self.children: child.notify(ground, subs,",
"'Substitutions'] class Root: def __init__(self): self.children = set() def notify(self,",
"class Root: def __init__(self): self.children = set() def notify(self, ground:",
"= root self.agenda = agenda parent.children.add(self) def notify(self, ground: List['Literal'],",
"[] table = {} root = Root() for rule in",
"ground_1: List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'): subs =",
"= repr(rule) self.memory = [] self.root = root self.agenda =",
"= (ground, subs) if payload not in self.memory: self.memory.append(payload) lit",
"(ground, subs) if payload not in self.memory: self.memory.append(payload) lit =",
"is RuleType.STRICT: # fact = Rule(lit, self.rule.type, []) # if",
"__init__(self): self.children = set() def notify(self, ground: 'Literal'): for child",
"List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): if parent is self.parent_1:",
"ground_2: List['Literal'], subs_2: 'Substitutions'): subs = self._unifies(subs_1, subs_2) if subs",
"for lit in rule.body: name = repr(lit) alfa = table.setdefault(name,",
"Union[Alfa, Beta], root: Root, agenda: List): self.parent = parent self.rule",
"typing import Union Payload = Tuple[List['Literal'], 'Substitutions'] class Root: def",
"self.name = repr(pattern) self.memory = [] self.children = set() parent.children.add(self)",
"None for lit in rule.body: name = repr(lit) alfa =",
"parent_1: Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1 = parent_1 self.parent_2 =",
"self._unifies(subs_1, subs_2) if subs is not None: ground = [*ground_1,",
"ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): from depysible.domain.definitions import",
"def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): from",
"not None: payload = ([ground], subs) if payload not in",
"parent_1 self.parent_2 = parent_2 self.name = '%s, %s' % (parent_1.name,",
"__init__(self, rule: 'Rule', parent: Union[Alfa, Beta], root: Root, agenda: List):",
"Beta: def __init__(self, parent_1: Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1 =",
"self.pattern = pattern self.name = repr(pattern) self.memory = [] self.children",
"parent_2.name) self.memory = [] self.children = set() parent_1.children.add(self) parent_2.children.add(self) def",
"<reponame>stefano-bragaglia/DePYsible from typing import List from typing import Optional from",
"child in self.children: child.notify([ground], subs, self) class Beta: def __init__(self,",
"= '%s, %s' % (parent_1.name, parent_2.name) self.memory = [] self.children",
"ground) if rule not in self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program:",
"subs_1: 'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'): subs = self._unifies(subs_1, subs_2)",
"parent self.pattern = pattern self.name = repr(pattern) self.memory = []",
"([ground], subs) if payload not in self.memory: self.memory.append(payload) for child",
"subs = self._unifies(subs_1, subs_2) if subs is not None: ground",
"None: payload = ([ground], subs) if payload not in self.memory:",
"'Literal', subs: 'Substitutions', parent: Root): subs = self.pattern.unifies(ground) if subs",
"self.children: child.notify(ground, subs, self) class Leaf: def __init__(self, rule: 'Rule',",
"program.is_ground(): return program rules = [] table = {} root",
"[] self.children = set() parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground: List['Literal'],",
"import Union Payload = Tuple[List['Literal'], 'Substitutions'] class Root: def __init__(self):",
"root = Root() for rule in program.rules: if rule.is_fact(): rules.append(rule)",
"# self.agenda.append(fact) rule = Rule(lit, self.rule.type, ground) if rule not",
"lit = self.rule.head.substitutes(subs) # if self.rule.type is RuleType.STRICT: # fact",
"alfa.name) beta = table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta, root, rules)",
"List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'): subs = self._unifies(subs_1,",
"Leaf: def __init__(self, rule: 'Rule', parent: Union[Alfa, Beta], root: Root,",
"-> List['Rule']: if program.is_ground(): return program rules = [] table",
"program rules = [] table = {} root = Root()",
"self.name = repr(rule) self.memory = [] self.root = root self.agenda",
"parent.children.add(self) def notify(self, ground: 'Literal', subs: 'Substitutions', parent: Root): subs",
"notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): if parent",
"if subs is not None: payload = ([ground], subs) if",
"Beta], root: Root, agenda: List): self.parent = parent self.rule =",
"self.rule.head.substitutes(subs) # if self.rule.type is RuleType.STRICT: # fact = Rule(lit,",
"'Literal'): for child in self.children: child.notify(ground, {}, self) class Alfa:",
"= Rule(lit, self.rule.type, ground) if rule not in self.agenda: self.agenda.append(rule)",
"in self.memory: self.memory.append(payload) for child in self.children: child.notify(ground, subs, self)",
"def notify(self, ground: 'Literal', subs: 'Substitutions', parent: Root): subs =",
"ground_2, subs_2) elif parent is self.parent_2: for ground_1, subs_1 in",
"%s' % (parent_1.name, parent_2.name) self.memory = [] self.children = set()",
"rule.is_fact(): rules.append(rule) else: beta = None for lit in rule.body:",
"in set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]: return None return {**subs_1,",
"'%s, %s' % (beta.name, alfa.name) beta = table.setdefault(name, Beta(beta, alfa))",
"= repr(lit) alfa = table.setdefault(name, Alfa(lit, root)) if beta is",
"if rule.is_fact(): rules.append(rule) else: beta = None for lit in",
"self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program') -> List['Rule']: if program.is_ground():",
"import List from typing import Optional from typing import Tuple",
"self.memory: self.memory.append(payload) for child in self.children: child.notify(ground, subs, self) class",
"Alfa: def __init__(self, pattern: 'Literal', parent: Root): self.parent = parent",
"RuleType.STRICT: # fact = Rule(lit, self.rule.type, []) # if fact",
"subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs) @staticmethod def _unifies(subs_1:",
"in self.children: child.notify([ground], subs, self) class Beta: def __init__(self, parent_1:",
"= table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta, root, rules) for fact",
"self.children: child.notify(ground, {}, self) class Alfa: def __init__(self, pattern: 'Literal',",
"rule self.name = repr(rule) self.memory = [] self.root = root",
"notify(self, ground: 'Literal', subs: 'Substitutions', parent: Root): subs = self.pattern.unifies(ground)",
"self.rule.type, ground) if rule not in self.agenda: self.agenda.append(rule) self.root.notify(lit) def",
"[*ground_1, *ground_2] payload = (ground, subs) if payload not in",
"in self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs) # if self.rule.type is",
"from typing import Union Payload = Tuple[List['Literal'], 'Substitutions'] class Root:",
"table.setdefault(name, Alfa(lit, root)) if beta is None: beta = alfa",
"= Root() for rule in program.rules: if rule.is_fact(): rules.append(rule) else:",
"return program rules = [] table = {} root =",
"set() parent.children.add(self) def notify(self, ground: 'Literal', subs: 'Substitutions', parent: Root):",
"in self.children: child.notify(ground, {}, self) class Alfa: def __init__(self, pattern:",
"parent: Root): self.parent = parent self.pattern = pattern self.name =",
"= alfa else: name = '%s, %s' % (beta.name, alfa.name)",
"typing import List from typing import Optional from typing import",
"= agenda parent.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent:",
"= repr(pattern) self.memory = [] self.children = set() parent.children.add(self) def",
"set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]: return None return {**subs_1, **subs_2}",
"if program.is_ground(): return program rules = [] table = {}",
"if self.rule.type is RuleType.STRICT: # fact = Rule(lit, self.rule.type, [])",
"Root): subs = self.pattern.unifies(ground) if subs is not None: payload",
"subs_2: 'Substitutions') -> Optional['Substitutions']: for var in set(subs_1).intersection(subs_2): if subs_1[var]",
"'Program') -> List['Rule']: if program.is_ground(): return program rules = []",
"root: Root, agenda: List): self.parent = parent self.rule = rule",
"'Beta']): from depysible.domain.definitions import Rule payload = (ground, subs) if",
"return None return {**subs_1, **subs_2} def _notify(self, ground_1: List['Literal'], subs_1:",
"if rule not in self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program')",
"self.memory = [] self.root = root self.agenda = agenda parent.children.add(self)",
"from typing import Optional from typing import Tuple from typing",
"Payload = Tuple[List['Literal'], 'Substitutions'] class Root: def __init__(self): self.children =",
"for child in self.children: child.notify(ground, {}, self) class Alfa: def",
"ground: 'Literal', subs: 'Substitutions', parent: Root): subs = self.pattern.unifies(ground) if",
"Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1 = parent_1 self.parent_2 = parent_2",
"payload = ([ground], subs) if payload not in self.memory: self.memory.append(payload)",
"self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs) @staticmethod def _unifies(subs_1: 'Substitutions', subs_2:",
"alfa = table.setdefault(name, Alfa(lit, root)) if beta is None: beta",
"# fact = Rule(lit, self.rule.type, []) # if fact not",
"self.parent = parent self.pattern = pattern self.name = repr(pattern) self.memory",
"repr(pattern) self.memory = [] self.children = set() parent.children.add(self) def notify(self,",
"root self.agenda = agenda parent.children.add(self) def notify(self, ground: List['Literal'], subs:",
"self.root = root self.agenda = agenda parent.children.add(self) def notify(self, ground:",
"subs_2 in self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2) elif parent is",
"= '%s, %s' % (beta.name, alfa.name) beta = table.setdefault(name, Beta(beta,",
"def notify(self, ground: 'Literal'): for child in self.children: child.notify(ground, {},",
"if payload not in self.memory: self.memory.append(payload) for child in self.children:",
"self.parent_2: for ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs)",
"payload not in self.memory: self.memory.append(payload) for child in self.children: child.notify(ground,",
"rules.append(rule) else: beta = None for lit in rule.body: name",
"for rule in program.rules: if rule.is_fact(): rules.append(rule) else: beta =",
"child.notify(ground, subs, self) class Leaf: def __init__(self, rule: 'Rule', parent:",
"depysible.domain.definitions import Rule payload = (ground, subs) if payload not",
"Leaf(rule, beta, root, rules) for fact in program.get_facts(): root.notify(fact.head) return",
"in self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs) @staticmethod def _unifies(subs_1: 'Substitutions',",
"in self.memory: self.memory.append(payload) for child in self.children: child.notify([ground], subs, self)",
"Beta(beta, alfa)) Leaf(rule, beta, root, rules) for fact in program.get_facts():",
"self.memory = [] self.children = set() parent_1.children.add(self) parent_2.children.add(self) def notify(self,",
"parent.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']):",
"self.memory = [] self.children = set() parent.children.add(self) def notify(self, ground:",
"beta, root, rules) for fact in program.get_facts(): root.notify(fact.head) return rules",
"parent_2: Alfa): self.parent_1 = parent_1 self.parent_2 = parent_2 self.name =",
"# if self.rule.type is RuleType.STRICT: # fact = Rule(lit, self.rule.type,",
"'Rule', parent: Union[Alfa, Beta], root: Root, agenda: List): self.parent =",
"= [] self.children = set() parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground:",
"self) class Alfa: def __init__(self, pattern: 'Literal', parent: Root): self.parent",
"self.parent_2 = parent_2 self.name = '%s, %s' % (parent_1.name, parent_2.name)",
"{**subs_1, **subs_2} def _notify(self, ground_1: List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'],",
"= [] self.root = root self.agenda = agenda parent.children.add(self) def",
"self.children = set() def notify(self, ground: 'Literal'): for child in",
"in self.children: child.notify(ground, subs, self) class Leaf: def __init__(self, rule:",
"self.children = set() parent.children.add(self) def notify(self, ground: 'Literal', subs: 'Substitutions',",
"= set() parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions',",
"= ([ground], subs) if payload not in self.memory: self.memory.append(payload) for",
"Alfa(lit, root)) if beta is None: beta = alfa else:",
"import Rule payload = (ground, subs) if payload not in",
"parent_2 self.name = '%s, %s' % (parent_1.name, parent_2.name) self.memory =",
"'Literal', parent: Root): self.parent = parent self.pattern = pattern self.name",
"pattern: 'Literal', parent: Root): self.parent = parent self.pattern = pattern",
"subs_2) elif parent is self.parent_2: for ground_1, subs_1 in self.parent_1.memory:",
"ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs) @staticmethod def",
"'Substitutions'): subs = self._unifies(subs_1, subs_2) if subs is not None:",
"= None for lit in rule.body: name = repr(lit) alfa",
"beta = table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta, root, rules) for",
"self.parent_1 = parent_1 self.parent_2 = parent_2 self.name = '%s, %s'",
"class Leaf: def __init__(self, rule: 'Rule', parent: Union[Alfa, Beta], root:",
"= Tuple[List['Literal'], 'Substitutions'] class Root: def __init__(self): self.children = set()",
"self.memory.append(payload) for child in self.children: child.notify(ground, subs, self) class Leaf:",
"= parent self.pattern = pattern self.name = repr(pattern) self.memory =",
"child.notify(ground, {}, self) class Alfa: def __init__(self, pattern: 'Literal', parent:",
"subs, self) class Leaf: def __init__(self, rule: 'Rule', parent: Union[Alfa,",
"None: ground = [*ground_1, *ground_2] payload = (ground, subs) if",
"else: name = '%s, %s' % (beta.name, alfa.name) beta =",
"% (parent_1.name, parent_2.name) self.memory = [] self.children = set() parent_1.children.add(self)",
"= set() def notify(self, ground: 'Literal'): for child in self.children:",
"is None: beta = alfa else: name = '%s, %s'",
"ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): if parent is",
"Alfa): self.parent_1 = parent_1 self.parent_2 = parent_2 self.name = '%s,",
"typing import Tuple from typing import Union Payload = Tuple[List['Literal'],",
"ground: 'Literal'): for child in self.children: child.notify(ground, {}, self) class",
"% (beta.name, alfa.name) beta = table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta,",
"set() parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent:",
"(beta.name, alfa.name) beta = table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta, root,",
"for ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1, ground, subs) @staticmethod",
"set() def notify(self, ground: 'Literal'): for child in self.children: child.notify(ground,",
"rule.body: name = repr(lit) alfa = table.setdefault(name, Alfa(lit, root)) if",
"= {} root = Root() for rule in program.rules: if",
"{} root = Root() for rule in program.rules: if rule.is_fact():",
"Tuple from typing import Union Payload = Tuple[List['Literal'], 'Substitutions'] class",
"parent: Union[Alfa, 'Beta']): from depysible.domain.definitions import Rule payload = (ground,",
"Rule(lit, self.rule.type, []) # if fact not in self.agenda: #",
"parent: Union[Alfa, 'Beta']): if parent is self.parent_1: for ground_2, subs_2",
"rule = Rule(lit, self.rule.type, ground) if rule not in self.agenda:",
"for child in self.children: child.notify(ground, subs, self) class Leaf: def",
"else: beta = None for lit in rule.body: name =",
"subs is not None: ground = [*ground_1, *ground_2] payload =",
"subs = self.pattern.unifies(ground) if subs is not None: payload =",
"= self._unifies(subs_1, subs_2) if subs is not None: ground =",
"Rule payload = (ground, subs) if payload not in self.memory:",
"self.parent_1: for ground_2, subs_2 in self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2)",
"in program.rules: if rule.is_fact(): rules.append(rule) else: beta = None for",
"self.children: child.notify([ground], subs, self) class Beta: def __init__(self, parent_1: Union[Alfa,",
"Root: def __init__(self): self.children = set() def notify(self, ground: 'Literal'):",
"List['Literal'], subs_2: 'Substitutions'): subs = self._unifies(subs_1, subs_2) if subs is",
"if parent is self.parent_1: for ground_2, subs_2 in self.parent_2.memory: self._notify(ground,",
"*ground_2] payload = (ground, subs) if payload not in self.memory:",
"self.parent = parent self.rule = rule self.name = repr(rule) self.memory",
"subs_2: 'Substitutions'): subs = self._unifies(subs_1, subs_2) if subs is not",
"def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): if",
"payload = (ground, subs) if payload not in self.memory: self.memory.append(payload)",
"self.rule.type, []) # if fact not in self.agenda: # self.agenda.append(fact)",
"beta is None: beta = alfa else: name = '%s,",
"Root): self.parent = parent self.pattern = pattern self.name = repr(pattern)",
"= [] table = {} root = Root() for rule",
"class Alfa: def __init__(self, pattern: 'Literal', parent: Root): self.parent =",
"List['Rule']: if program.is_ground(): return program rules = [] table =",
"for var in set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]: return None",
"'Beta'], parent_2: Alfa): self.parent_1 = parent_1 self.parent_2 = parent_2 self.name",
"fact not in self.agenda: # self.agenda.append(fact) rule = Rule(lit, self.rule.type,",
"subs_2) if subs is not None: ground = [*ground_1, *ground_2]",
"child in self.children: child.notify(ground, subs, self) class Leaf: def __init__(self,",
"'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'): subs = self._unifies(subs_1, subs_2) if",
"rule not in self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program') ->",
"def fire_rules(program: 'Program') -> List['Rule']: if program.is_ground(): return program rules",
"ground_2, subs_2 in self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2) elif parent",
"in self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2) elif parent is self.parent_2:",
"'%s, %s' % (parent_1.name, parent_2.name) self.memory = [] self.children =",
"parent is self.parent_2: for ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1, subs_1,",
"= rule self.name = repr(rule) self.memory = [] self.root =",
"{}, self) class Alfa: def __init__(self, pattern: 'Literal', parent: Root):",
"'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']: for var in set(subs_1).intersection(subs_2): if",
"Union[Alfa, 'Beta']): from depysible.domain.definitions import Rule payload = (ground, subs)",
"@staticmethod def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']: for var",
"for ground_2, subs_2 in self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2) elif",
"subs: 'Substitutions', parent: Root): subs = self.pattern.unifies(ground) if subs is",
"None: beta = alfa else: name = '%s, %s' %",
"None return {**subs_1, **subs_2} def _notify(self, ground_1: List['Literal'], subs_1: 'Substitutions',",
"= parent self.rule = rule self.name = repr(rule) self.memory =",
"if subs is not None: ground = [*ground_1, *ground_2] payload",
"'Substitutions', parent: Root): subs = self.pattern.unifies(ground) if subs is not",
"alfa)) Leaf(rule, beta, root, rules) for fact in program.get_facts(): root.notify(fact.head)",
"child.notify([ground], subs, self) class Beta: def __init__(self, parent_1: Union[Alfa, 'Beta'],",
"= parent_1 self.parent_2 = parent_2 self.name = '%s, %s' %",
"pattern self.name = repr(pattern) self.memory = [] self.children = set()",
"rules = [] table = {} root = Root() for",
"[] self.children = set() parent.children.add(self) def notify(self, ground: 'Literal', subs:",
"not in self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program') -> List['Rule']:",
"rule in program.rules: if rule.is_fact(): rules.append(rule) else: beta = None",
"_unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']: for var in set(subs_1).intersection(subs_2):",
"'Substitutions', parent: Union[Alfa, 'Beta']): from depysible.domain.definitions import Rule payload =",
"self.parent_2.memory: self._notify(ground, subs, ground_2, subs_2) elif parent is self.parent_2: for",
"fire_rules(program: 'Program') -> List['Rule']: if program.is_ground(): return program rules =",
"Root() for rule in program.rules: if rule.is_fact(): rules.append(rule) else: beta",
"for child in self.children: child.notify([ground], subs, self) class Beta: def",
"def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']: for var in",
"not None: ground = [*ground_1, *ground_2] payload = (ground, subs)",
"is self.parent_1: for ground_2, subs_2 in self.parent_2.memory: self._notify(ground, subs, ground_2,",
"subs, self) class Beta: def __init__(self, parent_1: Union[Alfa, 'Beta'], parent_2:",
"Rule(lit, self.rule.type, ground) if rule not in self.agenda: self.agenda.append(rule) self.root.notify(lit)",
"name = repr(lit) alfa = table.setdefault(name, Alfa(lit, root)) if beta",
"= parent_2 self.name = '%s, %s' % (parent_1.name, parent_2.name) self.memory",
"**subs_2} def _notify(self, ground_1: List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'], subs_2:",
"import Optional from typing import Tuple from typing import Union",
"from typing import Tuple from typing import Union Payload =",
"subs: 'Substitutions', parent: Union[Alfa, 'Beta']): if parent is self.parent_1: for",
"self.memory.append(payload) for child in self.children: child.notify([ground], subs, self) class Beta:",
"root)) if beta is None: beta = alfa else: name",
"[] self.root = root self.agenda = agenda parent.children.add(self) def notify(self,",
"subs_1, ground, subs) @staticmethod def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') ->",
"notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): from depysible.domain.definitions",
"'Substitutions') -> Optional['Substitutions']: for var in set(subs_1).intersection(subs_2): if subs_1[var] !=",
"!= subs_2[var]: return None return {**subs_1, **subs_2} def _notify(self, ground_1:",
"List from typing import Optional from typing import Tuple from",
"not in self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs) # if self.rule.type",
"is not None: payload = ([ground], subs) if payload not",
"fact = Rule(lit, self.rule.type, []) # if fact not in",
"Union Payload = Tuple[List['Literal'], 'Substitutions'] class Root: def __init__(self): self.children",
"= table.setdefault(name, Alfa(lit, root)) if beta is None: beta =",
"elif parent is self.parent_2: for ground_1, subs_1 in self.parent_1.memory: self._notify(ground_1,",
"if beta is None: beta = alfa else: name =",
"rule: 'Rule', parent: Union[Alfa, Beta], root: Root, agenda: List): self.parent",
"parent is self.parent_1: for ground_2, subs_2 in self.parent_2.memory: self._notify(ground, subs,",
"'Substitutions', parent: Union[Alfa, 'Beta']): if parent is self.parent_1: for ground_2,",
"if subs_1[var] != subs_2[var]: return None return {**subs_1, **subs_2} def",
"self._notify(ground, subs, ground_2, subs_2) elif parent is self.parent_2: for ground_1,",
"= [] self.children = set() parent.children.add(self) def notify(self, ground: 'Literal',",
"beta = alfa else: name = '%s, %s' % (beta.name,",
"(parent_1.name, parent_2.name) self.memory = [] self.children = set() parent_1.children.add(self) parent_2.children.add(self)",
"[]) # if fact not in self.agenda: # self.agenda.append(fact) rule",
"in self.agenda: self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program') -> List['Rule']: if",
"self.rule = rule self.name = repr(rule) self.memory = [] self.root",
"typing import Optional from typing import Tuple from typing import",
"table.setdefault(name, Beta(beta, alfa)) Leaf(rule, beta, root, rules) for fact in",
"import Tuple from typing import Union Payload = Tuple[List['Literal'], 'Substitutions']",
"parent: Union[Alfa, Beta], root: Root, agenda: List): self.parent = parent",
"payload not in self.memory: self.memory.append(payload) for child in self.children: child.notify([ground],",
"self.memory.append(payload) lit = self.rule.head.substitutes(subs) # if self.rule.type is RuleType.STRICT: #",
"ground, subs) @staticmethod def _unifies(subs_1: 'Substitutions', subs_2: 'Substitutions') -> Optional['Substitutions']:",
"self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs) # if self.rule.type is RuleType.STRICT:",
"beta = None for lit in rule.body: name = repr(lit)",
"table = {} root = Root() for rule in program.rules:",
"self.agenda.append(fact) rule = Rule(lit, self.rule.type, ground) if rule not in",
"subs_1[var] != subs_2[var]: return None return {**subs_1, **subs_2} def _notify(self,",
"# if fact not in self.agenda: # self.agenda.append(fact) rule =",
"var in set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]: return None return",
"payload not in self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs) # if",
"= pattern self.name = repr(pattern) self.memory = [] self.children =",
"in rule.body: name = repr(lit) alfa = table.setdefault(name, Alfa(lit, root))",
"parent_2.children.add(self) def notify(self, ground: List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']):",
"subs) if payload not in self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs)",
"class Beta: def __init__(self, parent_1: Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1",
"Root, agenda: List): self.parent = parent self.rule = rule self.name",
"subs_2[var]: return None return {**subs_1, **subs_2} def _notify(self, ground_1: List['Literal'],",
"def __init__(self, pattern: 'Literal', parent: Root): self.parent = parent self.pattern",
"%s' % (beta.name, alfa.name) beta = table.setdefault(name, Beta(beta, alfa)) Leaf(rule,",
"= (ground, subs) if payload not in self.memory: self.memory.append(payload) for",
"not in self.memory: self.memory.append(payload) for child in self.children: child.notify([ground], subs,",
"ground = [*ground_1, *ground_2] payload = (ground, subs) if payload",
"Optional from typing import Tuple from typing import Union Payload",
"def _notify(self, ground_1: List['Literal'], subs_1: 'Substitutions', ground_2: List['Literal'], subs_2: 'Substitutions'):",
"alfa else: name = '%s, %s' % (beta.name, alfa.name) beta",
"self.agenda: # self.agenda.append(fact) rule = Rule(lit, self.rule.type, ground) if rule",
"repr(lit) alfa = table.setdefault(name, Alfa(lit, root)) if beta is None:",
"(ground, subs) if payload not in self.memory: self.memory.append(payload) for child",
"self.name = '%s, %s' % (parent_1.name, parent_2.name) self.memory = []",
"self.pattern.unifies(ground) if subs is not None: payload = ([ground], subs)",
"__init__(self, parent_1: Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1 = parent_1 self.parent_2",
"Union[Alfa, 'Beta']): if parent is self.parent_1: for ground_2, subs_2 in",
"self.root.notify(lit) def fire_rules(program: 'Program') -> List['Rule']: if program.is_ground(): return program",
"child in self.children: child.notify(ground, {}, self) class Alfa: def __init__(self,",
"subs, ground_2, subs_2) elif parent is self.parent_2: for ground_1, subs_1",
"= Rule(lit, self.rule.type, []) # if fact not in self.agenda:",
"subs) if payload not in self.memory: self.memory.append(payload) for child in",
"if payload not in self.memory: self.memory.append(payload) lit = self.rule.head.substitutes(subs) #",
"not in self.agenda: # self.agenda.append(fact) rule = Rule(lit, self.rule.type, ground)",
"parent self.rule = rule self.name = repr(rule) self.memory = []",
"from typing import List from typing import Optional from typing",
"def __init__(self): self.children = set() def notify(self, ground: 'Literal'): for",
"self.agenda.append(rule) self.root.notify(lit) def fire_rules(program: 'Program') -> List['Rule']: if program.is_ground(): return",
"parent: Root): subs = self.pattern.unifies(ground) if subs is not None:",
"subs: 'Substitutions', parent: Union[Alfa, 'Beta']): from depysible.domain.definitions import Rule payload",
"self.rule.type is RuleType.STRICT: # fact = Rule(lit, self.rule.type, []) #",
"from depysible.domain.definitions import Rule payload = (ground, subs) if payload",
"lit in rule.body: name = repr(lit) alfa = table.setdefault(name, Alfa(lit,",
"= set() parent.children.add(self) def notify(self, ground: 'Literal', subs: 'Substitutions', parent:",
"notify(self, ground: 'Literal'): for child in self.children: child.notify(ground, {}, self)",
"name = '%s, %s' % (beta.name, alfa.name) beta = table.setdefault(name,",
"def __init__(self, rule: 'Rule', parent: Union[Alfa, Beta], root: Root, agenda:",
"self.children = set() parent_1.children.add(self) parent_2.children.add(self) def notify(self, ground: List['Literal'], subs:",
"__init__(self, pattern: 'Literal', parent: Root): self.parent = parent self.pattern =",
"-> Optional['Substitutions']: for var in set(subs_1).intersection(subs_2): if subs_1[var] != subs_2[var]:",
"def __init__(self, parent_1: Union[Alfa, 'Beta'], parent_2: Alfa): self.parent_1 = parent_1",
"return {**subs_1, **subs_2} def _notify(self, ground_1: List['Literal'], subs_1: 'Substitutions', ground_2:",
"self) class Leaf: def __init__(self, rule: 'Rule', parent: Union[Alfa, Beta],",
"List['Literal'], subs: 'Substitutions', parent: Union[Alfa, 'Beta']): from depysible.domain.definitions import Rule",
"repr(rule) self.memory = [] self.root = root self.agenda = agenda",
"List): self.parent = parent self.rule = rule self.name = repr(rule)"
] |
[
"+= 1 self.num_wins += 1 else: for last_action in current_last_actions:",
"self.current_hand_strength = 0.0 self.hand_class = '' self.hand_score = 0 self.current_game_state",
"for action in current_last_actions: if self.button: if 'FOLD' in action",
"== 1: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_two_bet =",
"round_num == 1: self.discard = True for action in current_last_actions:",
"= True self.current_pot_size = 0 self.current_hand = [] self.current_hand_strength =",
"0} self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet = False",
"0 self.fold_big_bet = 0 # opponent pre-flop stats self.opponent_pfr =",
"index = sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if action == 'CALL':",
"action: if self.button: for last_action in self.last_actions[-1]: if 'RAISE' in",
"in action: for last_action in current_last_actions: if 'BET' in last_action",
"= False self.showdown = 0 self.c_bet = 0 self.showdown_win =",
"== 1: self.discard = True for action in current_last_actions: if",
"+= 1 if self.current_game_state == 'PREFLOP': if self.street_dict['3'] > 0",
"last_action: sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True return None",
"in self.last_actions[-1]: if 'RAISE' in last_action and self.name in last_action:",
"+= 1 elif self.current_game_state == 'POSTRIVER': for action in current_last_actions:",
"action: if self.name in action: self.has_two_bet = True else: if",
"= 0 self.showdown_win = 0 self.double_barrel = 0 self.discarded_card =",
"True return None def hand_over(self, data_list): num_board_cards = data_list[3] index",
"last_action and self.name in last_action: self.opponent_fold_pfr += 1 if self.has_three_bet",
"self.showdown = 0 self.c_bet = 0 self.showdown_win = 0 self.double_barrel",
"current_last_actions: if 'RAISE' in action: if self.name in action: if",
"= action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard =",
"= [] self.last_actions = [] self.current_legal_actions = [] self.street_dict =",
"== 3: if self.name in action: self.pfr += 1 self.vpip",
"action in current_last_actions: if 'WIN' in action: if self.name in",
"False self.opponent_has_three_bet = False self.has_four_bet = False self.opponent_has_four_bet = False",
"self.double_barrel += 1 else: self.opponent_double_barrel += 1 break index +=",
"= self.street_dict['5'] if round_num == 1: for action in current_last_actions:",
"1 else: for last_action in current_last_actions: if 'RAISE' in last_action",
"self.last_actions = [] self.current_legal_actions = [] self.street_dict = {'0': 0,",
"Hand.hand_win_odds(self.current_hand) self.discard = False break if self.current_game_state == 'PREFLOP': if",
"self.current_pot_size = int(data_list[1]) self.opc = self.starting_stack_size - self.current_pot_size self.time_bank =",
"else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_four_bet = True",
"index = 3 + num_board_cards num_last_actions = int(data_list[index]) index +=",
"action in current_last_actions: if 'BET' in action: if self.name in",
"opponent pre-flop stats self.opponent_pfr = 0 self.opponent_vpip = 0 self.opponent_three_bet",
"== 'TURNRIVER': round_num = self.street_dict['4'] if round_num == 1: self.discard",
"current_last_actions: if 'RAISE' in action: round_num = self.street_dict['0'] if round_num",
"= False break if self.current_game_state == 'PREFLOP': if self.current_pot_size ==",
"board_cards = [] for board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand =",
"'RAISE': index = legal_action.index(':') + 1 sub = legal_action[index:] index",
"= Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 + num_board_cards num_last_actions = int(data_list[index])",
"self.has_four_bet = True else: self.has_three_bet = True break elif self.current_game_state",
"+= 1 self.num_wins += 1 else: if 'FOLD' in action",
"= '' self.hand_score = 0 self.current_game_state = '' self.board_cards =",
"in last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 elif self.current_game_state",
"stats self.name = name self.opponent_name = opponent_name self.starting_stack_size = int(stack_size)",
"1 self.opponent_vpip += 1 self.opponent_has_four_bet = True elif round_num ==",
"else: self.opponent_c_bet += 1 break elif round_num == 2: for",
"False self.time_bank = 0.0 self.opc = 0 def new_hand(self, data_list):",
"False self.has_bet_aggressively = False self.current_game_state = 'POSTRIVER' for i in",
"'BET' or action == 'RAISE': index = legal_action.index(':') + 1",
"and self.opponent_name in action: for last_action in current_last_actions: if 'BET'",
"in self.current_legal_actions: if action in legal_action: if action == 'BET'",
"\"true\" in self.button: self.button = True else: self.button = False",
"'FLOPTURN': if self.street_dict['4'] > 0 and self.street_dict['5'] == 0: self.has_two_bet",
"round_num == 4: for action in current_last_actions: if 'RAISE' in",
"if self.button: self.opponent_has_three_bet = True else: self.opponent_has_two_bet = True elif",
"if self.street_dict['5'] > 0: self.has_two_bet = False self.opponent_has_two_bet = False",
"if self.name in action: self.has_two_bet = True else: if self.button:",
"= sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if action == 'CALL': for",
"name, opponent_name, stack_size, bb): # match stats self.name = name",
"self.has_bet_aggressively = False self.time_bank = 0.0 self.opc = 0 def",
"0 and self.street_dict['5'] == 0: self.has_two_bet = False self.opponent_has_two_bet =",
"hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index =",
"0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet = 0 # self post-flop",
"= 0 self.c_bet = 0 self.showdown_win = 0 self.double_barrel =",
"= 0 self.opponent_vpip = 0 self.opponent_three_bet = 0 self.opponent_fold_pfr =",
"index += 1 current_last_actions = [] for i in range(num_last_actions):",
"1 else: self.opponent_vpip += 1 elif self.current_game_state == 'FLOPTURN': round_num",
"else: for last_action in current_last_actions: if 'RAISE' in last_action and",
"self.name in action: self.pfr += 1 self.vpip += 1 self.has_three_bet",
"range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if self.discard: for action in",
"'BET' in action: if self.name in action: self.double_barrel += 1",
"self.pfr = 0 self.vpip = 0 self.three_bet = 0 self.fold_big_bet",
"True else: self.opponent_has_two_bet = True elif round_num == 4: for",
"if 'FOLD' in action and self.opponent_name in action: for last_action",
"index = legal_action.index(':') + 1 sub = legal_action[index:] index =",
"self.current_legal_actions.append(data_list[index + i]) def legal_action(self, action): for legal_action in self.current_legal_actions:",
"1 sub = legal_action[index:] index = sub.index(':') return [int(sub[:index]), int(sub[index+1:])]",
"round_num = self.street_dict['3'] if round_num == 1: self.discard = True",
"for action in current_last_actions: if 'RAISE' in action: round_num =",
"index += num_last_actions num_legal_actions = int(data_list[index]) index += 1 self.current_legal_actions",
"= action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength =",
"self.has_three_bet = True else: self.opponent_pfr += 1 self.opponent_vpip += 1",
"if self.name in action: self.double_barrel += 1 else: self.opponent_double_barrel +=",
"self.vpip += 1 else: self.opponent_vpip += 1 elif self.current_game_state ==",
"== 4: for action in current_last_actions: if 'RAISE' in action:",
"1 self.button = data_list[2] if \"true\" in self.button: self.button =",
"if 'DISCARD' in action and self.name in action: old_card =",
"self.opponent_has_three_bet = False self.has_four_bet = False self.opponent_has_four_bet = False self.has_bet_aggressively",
"{'0': 0, '3': 0, '4': 0, '5': 0} self.discard =",
"num_board_cards > 0: board_cards = [] for board_card in self.board_cards:",
"self.street_dict['5'] if round_num == 1: for action in current_last_actions: if",
"== 'PREFLOP': for action in current_last_actions: if 'FOLD' in action",
"+= 1 self.opponent_has_three_bet = True else: if self.name in action:",
"False self.opponent_has_called = False self.has_two_bet = False self.opponent_has_two_bet = False",
"data_list[3] index = 4+num_board_cards num_last_actions = data_list[index] current_last_actions = []",
"current_last_actions: if self.button: if 'FOLD' in action and self.opponent_name in",
"'BET' in last_action and self.name in last_action: self.opponent_fold_c_bet += 1",
"= int(stack_size) self.num_hands = 0 self.num_wins = 0 self.num_flop =",
"elif 'CALL' in action: if self.name in action: self.vpip +=",
"self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet = False self.opponent_has_three_bet",
"0, '3': 0, '4': 0, '5': 0} self.has_two_bet = False",
"elif round_num == 2: for action in current_last_actions: if 'BET'",
"action: self.opponent_c_bet += 1 break elif round_num == 3: for",
"in current_last_actions: if 'DISCARD' in action and self.name in action:",
"== 'POSTRIVER': round_num = self.street_dict['5'] if round_num == 1: for",
"int(data_list[1]) self.opc = self.starting_stack_size - self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards",
"'POSTRIVER': round_num = self.street_dict['5'] if round_num == 1: for action",
"= 0 self.double_barrel = 0 self.discarded_card = None # opponent",
"self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_four_bet = True elif",
"num_board_cards = data_list[3] index = 4+num_board_cards num_last_actions = data_list[index] current_last_actions",
"range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP': for action in current_last_actions:",
"= True elif round_num == 3: if self.name in action:",
"in self.last_actions[-1]: if 'BET' in last_action and self.name in last_action:",
"self.opponent_has_two_bet = True elif round_num == 4: for action in",
"1 elif self.current_game_state == 'FLOPTURN': for action in current_last_actions: if",
"i]) self.last_actions.append(current_last_actions) if self.discard: for action in current_last_actions: if 'DISCARD'",
"1 else: self.opponent_c_bet += 1 elif 'RAISE' in action: if",
"self.name in action: self.num_wins += 1 for last_action in current_last_actions:",
"1 self.num_wins += 1 else: for last_action in current_last_actions: if",
"= 0 self.current_hand = [] self.current_hand_strength = 0.0 self.hand_class =",
"== 'FLOPTURN': if self.street_dict['4'] > 0 and self.street_dict['5'] == 0:",
"action: if self.button: self.has_four_bet = True else: self.has_three_bet = True",
"3: for action in current_last_actions: if 'BET' in action: if",
"self.time_bank = float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if",
"opponent_name self.starting_stack_size = int(stack_size) self.num_hands = 0 self.num_wins = 0",
"self.has_two_bet = True else: self.opponent_pfr += 1 self.opponent_vpip += 1",
"self.last_actions[-1]: if 'RAISE' in last_action and self.name in last_action: self.opponent_fold_pfr",
"break if self.current_game_state == 'PREFLOP': if self.current_pot_size == 4: if",
"[data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards =",
"1: self.discard = True elif round_num == 2: for action",
"+= 1 break elif round_num == 3: for action in",
"'FLOPTURN' self.num_flop += 1 elif self.current_game_state == 'FLOPTURN': if self.street_dict['4']",
"if round_num == 1: self.opponent_pfr += 1 self.opponent_vpip += 1",
"= False self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state",
"= float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if self.current_game_state",
"in current_last_actions: if 'SHOW' in last_action: self.showdown += 1 self.showdown_win",
"self.has_bet_aggressively = False self.current_game_state = 'FLOPTURN' self.num_flop += 1 elif",
"current_last_actions: if 'BET' in action: if self.name in action: self.c_bet",
"'TURNRIVER' elif self.current_game_state == 'TURNRIVER': if self.street_dict['5'] > 0: self.has_two_bet",
"0 self.big_blind = int(bb) # self pre-flop stats self.pfr =",
"self.vpip = 0 self.three_bet = 0 self.fold_big_bet = 0 #",
"stats self.opponent_c_bet = 0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel = 0",
"if self.button: self.vpip += 1 self.has_called = True else: self.opponent_vpip",
"and self.opponent_name in action: if self.button: for last_action in self.last_actions[-1]:",
"'FOLD' in action and self.opponent_name in action: if self.button: for",
"action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard = False",
"0 self.num_flop = 0 self.big_blind = int(bb) # self pre-flop",
"= [] self.current_hand_strength = 0.0 self.hand_class = '' self.hand_score =",
"'3': 0, '4': 0, '5': 0} self.discard = False self.has_five_bet",
"self.num_wins += 1 elif self.current_game_state == 'FLOPTURN': for action in",
"in current_last_actions: if 'BET' in action: if self.name in action:",
"= False self.has_three_bet = False self.opponent_has_three_bet = False self.has_four_bet =",
"in current_last_actions: if 'BET' in action: self.opponent_c_bet += 1 break",
"stack_size, bb): # match stats self.name = name self.opponent_name =",
"False break if self.current_game_state == 'PREFLOP': if self.current_pot_size == 4:",
"[] for board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand = [] for",
"current hand stats self.button = True self.current_pot_size = 0 self.current_hand",
"self.num_hands += 1 self.button = data_list[2] if \"true\" in self.button:",
"+= 1 else: self.opponent_double_barrel += 1 break index += num_last_actions",
"return [int(sub[:index]), int(sub[index+1:])] if action == 'CALL': for last_action in",
"# opponent post-flop stats self.opponent_c_bet = 0 self.opponent_fold_c_bet = 0",
"4: if self.button: self.vpip += 1 self.has_called = True else:",
"self.num_hands = 0 self.num_wins = 0 self.num_flop = 0 self.big_blind",
"self.vpip += 1 self.has_three_bet = True else: self.opponent_pfr += 1",
"self.opponent_vpip += 1 self.opponent_has_four_bet = True elif round_num == 3:",
"== 3: for action in current_last_actions: if 'BET' in action:",
"self.has_three_bet = True break elif self.current_game_state == 'POSTRIVER': round_num =",
"self.current_pot_size = 0 self.current_hand = [] self.current_hand_strength = 0.0 self.hand_class",
"False self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet = False",
"else: self.button = False self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength =",
"and self.street_dict['5'] == 0: self.has_two_bet = False self.opponent_has_two_bet = False",
"= 0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel = 0 # current",
"= 'PREFLOP' self.board_cards = [] self.last_actions = [] self.current_legal_actions =",
"self.opponent_fold_three_bet += 1 self.num_wins += 1 else: for last_action in",
"self.name in last_action: self.opponent_fold_pfr += 1 if self.has_three_bet and not",
"last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 elif self.current_game_state ==",
"self.has_two_bet = True else: if self.button: self.opponent_has_three_bet = True else:",
"return True return None def hand_over(self, data_list): num_board_cards = data_list[3]",
"pre-flop stats self.pfr = 0 self.vpip = 0 self.three_bet =",
"deuces.deuces import Card, Evaluator class GameData: def __init__(self, name, opponent_name,",
"stats self.opponent_pfr = 0 self.opponent_vpip = 0 self.opponent_three_bet = 0",
"False self.has_bet_aggressively = False self.aggression_factor = False self.discarded_card = None",
"self.current_legal_actions = [] self.street_dict = {'0': 0, '3': 0, '4':",
"= self.starting_stack_size - self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards = int(data_list[2])",
"== 'RAISE': index = legal_action.index(':') + 1 sub = legal_action[index:]",
"sub = legal_action[index:] index = sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if",
"1 self.opponent_has_called = True else: for action in current_last_actions: if",
"= [] for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def",
"1 self.num_wins += 1 elif self.current_game_state == 'FLOPTURN': for action",
"= False self.discarded_card = None def get_action(self, data_list): self.current_pot_size =",
"action in legal_action: if action == 'BET' or action ==",
"self.opponent_fold_c_bet = 0 self.opponent_double_barrel = 0 # current hand stats",
"self.pfr += 1 self.vpip += 1 self.has_three_bet = True else:",
"self.opponent_fold_three_bet = 0 # self post-flop stats self.aggression_factor = False",
"in action and self.opponent_name in action: for last_action in current_last_actions:",
"if num_board_cards > 0: board_cards = [] for board_card in",
"'FLOPTURN': for action in current_last_actions: if self.button: if 'FOLD' in",
"self.opponent_has_called = False self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet",
"in current_last_actions: if self.button: if 'FOLD' in action and self.opponent_name",
"data_list[3 + i] if board_card not in self.board_cards: self.board_cards.append(data_list[3 +",
"as Hand from deuces.deuces import Card, Evaluator class GameData: def",
"self.vpip += 1 self.has_two_bet = True else: self.opponent_pfr += 1",
"last_action in current_last_actions: if 'SHOW' in last_action: self.showdown += 1",
"= [] for board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand = []",
"= [] self.current_legal_actions = [] self.street_dict = {'0': 0, '3':",
"self.opponent_double_barrel = 0 # current hand stats self.button = True",
"== 'BET' or action == 'RAISE': index = legal_action.index(':') +",
"1 self.vpip += 1 self.has_three_bet = True else: self.opponent_pfr +=",
"num_last_actions num_legal_actions = int(data_list[index]) index += 1 self.current_legal_actions = []",
"new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard",
"[] self.current_hand_strength = 0.0 self.hand_class = '' self.hand_score = 0",
"= True else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_four_bet",
"self.current_game_state = 'PREFLOP' self.board_cards = [] self.last_actions = [] self.current_legal_actions",
"round_num == 3: for action in current_last_actions: if 'BET' in",
"self.current_game_state == 'PREFLOP': if self.street_dict['3'] > 0 and self.street_dict['4'] ==",
"'FOLD' in action and self.opponent_name in action: for last_action in",
"+= 1 break elif round_num == 2: for action in",
"if round_num == 1: for action in current_last_actions: if 'BET'",
"action: round_num = self.street_dict['0'] if round_num == 1: self.opponent_pfr +=",
"False self.discarded_card = None def get_action(self, data_list): self.current_pot_size = int(data_list[1])",
"in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def legal_action(self, action): for legal_action",
"data_list): num_board_cards = data_list[3] index = 4+num_board_cards num_last_actions = data_list[index]",
"in action and self.opponent_name in action: if self.button: for last_action",
"self.opc = 0 def new_hand(self, data_list): self.num_hands += 1 self.button",
"= 4+num_board_cards num_last_actions = data_list[index] current_last_actions = [] for i",
"= False self.has_four_bet = False self.opponent_has_four_bet = False self.street_dict =",
"3 + num_board_cards num_last_actions = int(data_list[index]) index += 1 current_last_actions",
"current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if self.discard: for action in current_last_actions:",
"1 elif 'RAISE' in action: if self.name in action: self.has_two_bet",
"current_last_actions: if 'DISCARD' in action and self.name in action: old_card",
"round_num == 1: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_two_bet",
"elif 'RAISE' in action: if self.name in action: self.has_two_bet =",
"'DISCARD' in action and self.name in action: old_card = action[8:10]",
"self.opponent_name = opponent_name self.starting_stack_size = int(stack_size) self.num_hands = 0 self.num_wins",
"True elif round_num == 2: for action in current_last_actions: if",
"False self.opponent_has_two_bet = False self.has_three_bet = False self.opponent_has_three_bet = False",
"action in current_last_actions: if self.button: if 'FOLD' in action and",
"self.street_dict['5'] > 0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet",
"else: self.opponent_double_barrel += 1 break index += num_last_actions num_legal_actions =",
"2: for action in current_last_actions: if 'BET' in action: self.opponent_c_bet",
"in action: self.pfr += 1 self.vpip += 1 self.has_two_bet =",
"4+num_board_cards num_last_actions = data_list[index] current_last_actions = [] for i in",
"== 'TURNRIVER': if self.street_dict['5'] > 0: self.has_two_bet = False self.opponent_has_two_bet",
"+= 1 elif 'CALL' in action: if self.name in action:",
"[] for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def legal_action(self,",
"elif self.current_game_state == 'POSTRIVER': for action in current_last_actions: if 'WIN'",
"False self.has_bet_aggressively = False self.current_game_state = 'TURNRIVER' elif self.current_game_state ==",
"if self.name in action: if self.button: self.has_four_bet = True else:",
"self.current_game_state == 'PREFLOP': for action in current_last_actions: if 'FOLD' in",
"self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 else: for last_action",
"break elif round_num == 3: for action in current_last_actions: if",
"self.opponent_has_four_bet = False self.has_bet_aggressively = False self.aggression_factor = False self.discarded_card",
"0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet = False",
"else: self.opponent_vpip += 1 elif self.current_game_state == 'FLOPTURN': round_num =",
"else: self.opponent_c_bet += 1 elif 'RAISE' in action: if self.name",
"0.0 self.opc = 0 def new_hand(self, data_list): self.num_hands += 1",
"None def get_action(self, data_list): self.current_pot_size = int(data_list[1]) self.opc = self.starting_stack_size",
"self.current_game_state == 'FLOPTURN': round_num = self.street_dict['3'] if round_num == 1:",
"= False self.current_game_state = 'FLOPTURN' self.num_flop += 1 elif self.current_game_state",
"+= 1 elif self.current_game_state == 'FLOPTURN': if self.street_dict['4'] > 0",
"self.num_wins = 0 self.num_flop = 0 self.big_blind = int(bb) #",
"[] for card in self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards)",
"== 'PREFLOP': if self.street_dict['3'] > 0 and self.street_dict['4'] == 0:",
"= 0 self.current_game_state = '' self.board_cards = [] self.last_actions =",
"self.button: self.button = True else: self.button = False self.current_hand =",
"self.street_dict['0'] if round_num == 1: self.opponent_pfr += 1 self.opponent_vpip +=",
"action: old_card = action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card",
"2: if self.button: if self.name in action: self.pfr += 1",
"int(data_list[index]) index += 1 self.current_legal_actions = [] for i in",
"= data_list[3] index = 4+num_board_cards num_last_actions = data_list[index] current_last_actions =",
"self.opponent_fold_pfr = 0 self.opponent_fold_three_bet = 0 # self post-flop stats",
"in self.button: self.button = True else: self.button = False self.current_hand",
"for action in current_last_actions: if 'BET' in action: self.opponent_c_bet +=",
"return None def hand_over(self, data_list): num_board_cards = data_list[3] index =",
"0, '4': 0, '5': 0} self.has_two_bet = False self.opponent_has_two_bet =",
"True else: self.button = False self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength",
"GameData: def __init__(self, name, opponent_name, stack_size, bb): # match stats",
"= None # opponent post-flop stats self.opponent_c_bet = 0 self.opponent_fold_c_bet",
"post-flop stats self.opponent_c_bet = 0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel =",
"[] for i in range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if",
"and self.name in action: old_card = action[8:10] new_card = action[11:13]",
"self.name in action: self.pfr += 1 self.vpip += 1 self.has_two_bet",
"if self.button: self.has_four_bet = True else: self.has_three_bet = True break",
"self.street_dict['3'] if round_num == 1: self.discard = True elif round_num",
"1 elif self.current_game_state == 'FLOPTURN': round_num = self.street_dict['3'] if round_num",
"self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'TURNRIVER' elif",
"board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand = [] for card in",
"action in current_last_actions: if 'BET' in action: self.opponent_c_bet += 1",
"for action in current_last_actions: if 'WIN' in action: if self.name",
"+= 1 self.opponent_vpip += 1 self.opponent_has_three_bet = True else: if",
"= 0 # opponent pre-flop stats self.opponent_pfr = 0 self.opponent_vpip",
"Card, Evaluator class GameData: def __init__(self, name, opponent_name, stack_size, bb):",
"self.has_bet_aggressively = False self.aggression_factor = False self.discarded_card = None def",
"1 elif 'CALL' in action: if self.name in action: self.vpip",
"== 1: for action in current_last_actions: if 'BET' in action:",
"0, '5': 0} self.discard = False self.has_five_bet = False self.has_bet_aggressively",
"True else: self.opponent_vpip += 1 self.opponent_has_called = True else: for",
"not in self.board_cards: self.board_cards.append(data_list[3 + i]) if num_board_cards > 0:",
"legal_action(self, action): for legal_action in self.current_legal_actions: if action in legal_action:",
"i] if board_card not in self.board_cards: self.board_cards.append(data_list[3 + i]) if",
"+ i]) if num_board_cards > 0: board_cards = [] for",
"int(sub[index+1:])] if action == 'CALL': for last_action in self.last_actions[-1]: if",
"action and self.opponent_name in action: for last_action in current_last_actions: if",
"round_num = self.street_dict['0'] if round_num == 1: self.opponent_pfr += 1",
"= False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.aggression_factor =",
"+= 1 break index += num_last_actions num_legal_actions = int(data_list[index]) index",
"for last_action in current_last_actions: if 'SHOW' in last_action: self.showdown +=",
"in current_last_actions: if 'RAISE' in last_action and self.name in last_action:",
"index += 1 self.current_legal_actions = [] for i in range(num_legal_actions):",
"0, '4': 0, '5': 0} self.discard = False self.has_five_bet =",
"else: for action in current_last_actions: if 'RAISE' in action: round_num",
"in action: if self.name in action: if self.button: self.has_four_bet =",
"action: for last_action in self.last_actions[-1]: if 'BET' in last_action and",
"= None def get_action(self, data_list): self.current_pot_size = int(data_list[1]) self.opc =",
"current_last_actions: if 'SHOW' in last_action: self.showdown += 1 self.showdown_win +=",
"+= 1 self.current_legal_actions = [] for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index",
"= False self.street_dict = {'0': 0, '3': 0, '4': 0,",
"self.opponent_name in action: if self.button: for last_action in self.last_actions[-1]: if",
"False self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state =",
"+= 1 self.vpip += 1 self.has_three_bet = True else: self.opponent_pfr",
"'' self.board_cards = [] self.last_actions = [] self.current_legal_actions = []",
"in legal_action: if action == 'BET' or action == 'RAISE':",
"in last_action and self.opponent_name in last_action: sub = last_action[last_action.index(':')+1:] return",
"self.opponent_name in action: for last_action in self.last_actions[-1]: if 'BET' in",
"old_card = action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength",
"self.button: if 'FOLD' in action and self.opponent_name in action: for",
"+= 1 if self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet += 1",
"False self.has_bet_aggressively = False self.time_bank = 0.0 self.opc = 0",
"self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'POSTRIVER' for",
"if board_card not in self.board_cards: self.board_cards.append(data_list[3 + i]) if num_board_cards",
"False self.has_five_bet = False self.has_bet_aggressively = False self.time_bank = 0.0",
"int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if self.current_game_state == 'PREFLOP': if self.street_dict['3']",
"data_list): self.num_hands += 1 self.button = data_list[2] if \"true\" in",
"for action in current_last_actions: if 'FOLD' in action and self.opponent_name",
"+= 1 self.num_wins += 1 elif self.current_game_state == 'FLOPTURN': for",
"self.showdown_win = 0 self.double_barrel = 0 self.discarded_card = None #",
"self.has_five_bet = False self.has_bet_aggressively = False self.time_bank = 0.0 self.opc",
"= False self.has_bet_aggressively = False self.current_game_state = 'FLOPTURN' self.num_flop +=",
"self.num_wins += 1 else: if 'FOLD' in action and self.opponent_name",
"0 self.opponent_double_barrel = 0 # current hand stats self.button =",
"+= 1 else: if 'FOLD' in action and self.opponent_name in",
"if self.street_dict['3'] > 0 and self.street_dict['4'] == 0: self.has_two_bet =",
"elif self.current_game_state == 'TURNRIVER': round_num = self.street_dict['4'] if round_num ==",
"in self.board_cards: board_cards.append(Card.new(board_card)) hand = [] for card in self.current_hand:",
"last_action in self.last_actions[-1]: if 'RAISE' in last_action and self.opponent_name in",
"0 # self post-flop stats self.aggression_factor = False self.showdown =",
"1 self.current_legal_actions = [] for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index +",
"[] for i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP':",
"'BET' in action: self.opponent_c_bet += 1 break elif round_num ==",
"round_num = self.street_dict['5'] if round_num == 1: for action in",
"0: board_cards = [] for board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand",
"in self.board_cards: self.board_cards.append(data_list[3 + i]) if num_board_cards > 0: board_cards",
"round_num == 2: if self.button: if self.name in action: self.pfr",
"= [] self.has_called = False self.opponent_has_called = False self.has_two_bet =",
"+ i]) self.last_actions.append(current_last_actions) if self.discard: for action in current_last_actions: if",
"self.name in action: self.double_barrel += 1 else: self.opponent_double_barrel += 1",
"= False self.opponent_has_three_bet = False self.has_four_bet = False self.opponent_has_four_bet =",
"= new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard = False break if",
"current_last_actions: if 'RAISE' in last_action and self.name in last_action: self.opponent_fold_pfr",
"= [] for card in self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand,",
"= 0 self.vpip = 0 self.three_bet = 0 self.fold_big_bet =",
"in last_action and self.name in last_action: self.opponent_fold_pfr += 1 if",
"+= 1 self.has_called = True else: self.opponent_vpip += 1 self.opponent_has_called",
"self.opponent_pfr = 0 self.opponent_vpip = 0 self.opponent_three_bet = 0 self.opponent_fold_pfr",
"self.discard = False break if self.current_game_state == 'PREFLOP': if self.current_pot_size",
"+= 1 else: for last_action in current_last_actions: if 'RAISE' in",
"True break elif self.current_game_state == 'POSTRIVER': round_num = self.street_dict['5'] if",
"hand_over(self, data_list): num_board_cards = data_list[3] index = 4+num_board_cards num_last_actions =",
"= 3 + num_board_cards num_last_actions = int(data_list[index]) index += 1",
"+ i]) def legal_action(self, action): for legal_action in self.current_legal_actions: if",
"sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True return None def",
"= True else: self.opponent_has_two_bet = True elif round_num == 4:",
"if 'RAISE' in last_action and self.name in last_action: self.opponent_fold_pfr +=",
"0} self.discard = False self.has_five_bet = False self.has_bet_aggressively = False",
"> 0: board_cards = [] for board_card in self.board_cards: board_cards.append(Card.new(board_card))",
"= 0 self.opponent_fold_three_bet = 0 # self post-flop stats self.aggression_factor",
"elif self.current_game_state == 'FLOPTURN': if self.street_dict['4'] > 0 and self.street_dict['5']",
"self.current_game_state = 'FLOPTURN' self.num_flop += 1 elif self.current_game_state == 'FLOPTURN':",
"1 current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index +",
"0 self.discarded_card = None # opponent post-flop stats self.opponent_c_bet =",
"self.vpip += 1 self.has_called = True else: self.opponent_vpip += 1",
"self.discard: for action in current_last_actions: if 'DISCARD' in action and",
"self.opponent_has_four_bet = False self.street_dict = {'0': 0, '3': 0, '4':",
"1 self.opponent_has_two_bet = True elif round_num == 2: if self.button:",
"= 0 self.opponent_double_barrel = 0 # current hand stats self.button",
"0 # current hand stats self.button = True self.current_pot_size =",
"action == 'RAISE': index = legal_action.index(':') + 1 sub =",
"self.name in last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 else:",
"= int(data_list[index]) index += 1 self.current_legal_actions = [] for i",
"True else: if self.button: self.opponent_has_three_bet = True else: self.opponent_has_two_bet =",
"legal_action[index:] index = sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if action ==",
"= False self.has_four_bet = False self.opponent_has_four_bet = False self.has_bet_aggressively =",
"in self.last_actions[-1]: if 'RAISE' in last_action and self.opponent_name in last_action:",
"self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP'",
"last_action in self.last_actions[-1]: if 'BET' in last_action and self.name in",
"+ num_board_cards num_last_actions = int(data_list[index]) index += 1 current_last_actions =",
"elif round_num == 3: if self.name in action: self.pfr +=",
"= True else: self.has_three_bet = True break elif self.current_game_state ==",
"+= 1 else: self.opponent_c_bet += 1 elif 'RAISE' in action:",
"and self.name in last_action: self.opponent_fold_pfr += 1 if self.has_three_bet and",
"1 elif self.current_game_state == 'POSTRIVER': for action in current_last_actions: if",
"self.current_game_state == 'POSTRIVER': round_num = self.street_dict['5'] if round_num == 1:",
"self.board_cards = [] self.last_actions = [] self.current_legal_actions = [] self.has_called",
"= 0 # self post-flop stats self.aggression_factor = False self.showdown",
"== 0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet =",
"[] self.current_legal_actions = [] self.has_called = False self.opponent_has_called = False",
"= False self.opponent_has_called = False self.has_two_bet = False self.opponent_has_two_bet =",
"board_card = data_list[3 + i] if board_card not in self.board_cards:",
"# opponent pre-flop stats self.opponent_pfr = 0 self.opponent_vpip = 0",
"'' self.hand_score = 0 self.current_game_state = '' self.board_cards = []",
"and self.opponent_name in action: for last_action in self.last_actions[-1]: if 'BET'",
"+= 1 self.button = data_list[2] if \"true\" in self.button: self.button",
"= opponent_name self.starting_stack_size = int(stack_size) self.num_hands = 0 self.num_wins =",
"opponent_name, stack_size, bb): # match stats self.name = name self.opponent_name",
"1 self.opponent_has_four_bet = True elif round_num == 3: if self.name",
"new_hand(self, data_list): self.num_hands += 1 self.button = data_list[2] if \"true\"",
"action in current_last_actions: if 'RAISE' in action: round_num = self.street_dict['0']",
"action in current_last_actions: if 'DISCARD' in action and self.name in",
"in action: self.pfr += 1 self.vpip += 1 self.has_three_bet =",
"else: self.opponent_vpip += 1 self.opponent_has_called = True else: for action",
"for card in self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class",
"in action: for last_action in self.last_actions[-1]: if 'BET' in last_action",
"action: self.pfr += 1 self.vpip += 1 self.has_three_bet = True",
"if round_num == 1: self.discard = True for action in",
"self.opponent_three_bet = 0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet = 0 #",
"[] self.last_actions = [] self.current_legal_actions = [] self.street_dict = {'0':",
"self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1",
"elif self.current_game_state == 'FLOPTURN': for action in current_last_actions: if self.button:",
"'CALL' in action: if self.name in action: self.vpip += 1",
"in current_last_actions: if 'BET' in last_action and self.name in last_action:",
"self.fold_big_bet = 0 # opponent pre-flop stats self.opponent_pfr = 0",
"= False self.has_bet_aggressively = False self.current_game_state = 'TURNRIVER' elif self.current_game_state",
"legal_action.index(':') + 1 sub = legal_action[index:] index = sub.index(':') return",
"elif self.current_game_state == 'TURNRIVER': if self.street_dict['5'] > 0: self.has_two_bet =",
"= int(bb) # self pre-flop stats self.pfr = 0 self.vpip",
"self.opponent_vpip = 0 self.opponent_three_bet = 0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet",
"self.button: self.opponent_has_three_bet = True else: self.opponent_has_two_bet = True elif round_num",
"self.hand_class = '' self.hand_score = 0 self.current_game_state = '' self.board_cards",
"self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3",
"elif round_num == 2: if self.button: if self.name in action:",
"action == 'BET' or action == 'RAISE': index = legal_action.index(':')",
"+= 1 self.num_wins += 1 elif self.current_game_state == 'POSTRIVER': for",
"in last_action and self.name in last_action: self.opponent_fold_c_bet += 1 self.num_wins",
"0 self.opponent_fold_three_bet = 0 # self post-flop stats self.aggression_factor =",
"1 self.num_wins += 1 elif self.current_game_state == 'POSTRIVER': for action",
"'PREFLOP': if self.current_pot_size == 4: if self.button: self.vpip += 1",
"in action: self.num_wins += 1 for last_action in current_last_actions: if",
"action: for last_action in current_last_actions: if 'BET' in last_action and",
"= 0.0 self.opc = 0 def new_hand(self, data_list): self.num_hands +=",
"in action: self.c_bet += 1 else: self.opponent_c_bet += 1 break",
"i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP': for action",
"for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def legal_action(self, action):",
"for last_action in current_last_actions: if 'BET' in last_action and self.name",
"data_list[2] if \"true\" in self.button: self.button = True else: self.button",
"self.hand_score = 0 self.current_game_state = '' self.board_cards = [] self.last_actions",
"if action in legal_action: if action == 'BET' or action",
"current_last_actions: if 'FOLD' in action and self.opponent_name in action: if",
"self.has_three_bet = False self.opponent_has_three_bet = False self.has_four_bet = False self.opponent_has_four_bet",
"self.has_four_bet = False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.aggression_factor",
"# match stats self.name = name self.opponent_name = opponent_name self.starting_stack_size",
"if self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins +=",
"in last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 else: if",
"action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand)",
"in current_last_actions: if 'FOLD' in action and self.opponent_name in action:",
"in action: self.has_two_bet = True else: if self.button: self.opponent_has_three_bet =",
"from deuces.deuces import Card, Evaluator class GameData: def __init__(self, name,",
"i in range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if self.discard: for",
"int(stack_size) self.num_hands = 0 self.num_wins = 0 self.num_flop = 0",
"= [] self.street_dict = {'0': 0, '3': 0, '4': 0,",
"board_card not in self.board_cards: self.board_cards.append(data_list[3 + i]) if num_board_cards >",
"self.name in action: self.vpip += 1 else: self.opponent_vpip += 1",
"self.current_legal_actions = [] self.has_called = False self.opponent_has_called = False self.has_two_bet",
"self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'FLOPTURN' self.num_flop",
"elif round_num == 3: for action in current_last_actions: if 'BET'",
"= data_list[3 + i] if board_card not in self.board_cards: self.board_cards.append(data_list[3",
"0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel = 0 # current hand",
"self.opponent_fold_c_bet += 1 self.num_wins += 1 elif self.current_game_state == 'POSTRIVER':",
"= False self.opponent_has_two_bet = False self.has_three_bet = False self.opponent_has_three_bet =",
"i in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def legal_action(self, action): for",
"= 0 def new_hand(self, data_list): self.num_hands += 1 self.button =",
"0, '3': 0, '4': 0, '5': 0} self.discard = False",
"i]) if num_board_cards > 0: board_cards = [] for board_card",
"return int(sub[:sub.index(':')]) return True return None def hand_over(self, data_list): num_board_cards",
"= False self.current_game_state = 'TURNRIVER' elif self.current_game_state == 'TURNRIVER': if",
"match stats self.name = name self.opponent_name = opponent_name self.starting_stack_size =",
"if action == 'BET' or action == 'RAISE': index =",
"self.name in action: if self.button: self.has_four_bet = True else: self.has_three_bet",
"{'0': 0, '3': 0, '4': 0, '5': 0} self.has_two_bet =",
"'SHOW' in last_action: self.showdown += 1 self.showdown_win += 1 break",
"False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.aggression_factor = False",
"= self.street_dict['0'] if round_num == 1: self.opponent_pfr += 1 self.opponent_vpip",
"self.vpip += 1 elif 'CALL' in action: if self.name in",
"if self.button: for last_action in self.last_actions[-1]: if 'RAISE' in last_action",
"self.street_dict['4'] > 0 and self.street_dict['5'] == 0: self.has_two_bet = False",
"if 'BET' in action: if self.name in action: self.double_barrel +=",
"else: if 'FOLD' in action and self.opponent_name in action: for",
"== 2: for action in current_last_actions: if 'BET' in action:",
"data_list): self.current_pot_size = int(data_list[1]) self.opc = self.starting_stack_size - self.current_pot_size self.time_bank",
"last_action: self.opponent_fold_pfr += 1 if self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet",
"in action and self.opponent_name in action: for last_action in self.last_actions[-1]:",
"= data_list[index] current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index+i])",
"self.name in action: old_card = action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)]",
"__init__(self, name, opponent_name, stack_size, bb): # match stats self.name =",
"= True else: self.opponent_vpip += 1 self.opponent_has_called = True else:",
"new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard = False break if self.current_game_state",
"self.current_hand = [] self.current_hand_strength = 0.0 self.hand_class = '' self.hand_score",
"for i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP': for",
"pre-flop stats self.opponent_pfr = 0 self.opponent_vpip = 0 self.opponent_three_bet =",
"'POSTRIVER' for i in range(num_board_cards): board_card = data_list[3 + i]",
"self.opponent_c_bet += 1 break elif round_num == 3: for action",
"action in current_last_actions: if 'FOLD' in action and self.opponent_name in",
"'TURNRIVER': round_num = self.street_dict['4'] if round_num == 1: self.discard =",
"current_last_actions: if 'WIN' in action: if self.name in action: self.num_wins",
"self.double_barrel = 0 self.discarded_card = None # opponent post-flop stats",
"= int(data_list[1]) self.opc = self.starting_stack_size - self.current_pot_size self.time_bank = float(data_list[-1])",
"1 self.opponent_vpip += 1 self.opponent_has_three_bet = True else: if self.name",
"1: self.discard = True for action in current_last_actions: if 'BET'",
"if self.name in action: self.pfr += 1 self.vpip += 1",
"for last_action in self.last_actions[-1]: if 'RAISE' in last_action and self.name",
"self.opponent_name in action: for last_action in current_last_actions: if 'BET' in",
"last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True return None def hand_over(self, data_list):",
"not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 elif self.current_game_state",
"== 1: self.discard = True elif round_num == 2: for",
"self pre-flop stats self.pfr = 0 self.vpip = 0 self.three_bet",
"if 'RAISE' in action: round_num = self.street_dict['0'] if round_num ==",
"if self.current_pot_size == 4: if self.button: self.vpip += 1 self.has_called",
"0 def new_hand(self, data_list): self.num_hands += 1 self.button = data_list[2]",
"False self.aggression_factor = False self.discarded_card = None def get_action(self, data_list):",
"= 0.0 self.hand_class = '' self.hand_score = 0 self.current_game_state =",
"not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 else: for",
"for last_action in self.last_actions[-1]: if 'BET' in last_action and self.name",
"+= 1 for last_action in current_last_actions: if 'SHOW' in last_action:",
"= 0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet = 0 # self",
"= False self.has_bet_aggressively = False self.time_bank = 0.0 self.opc =",
"self.board_cards = [] self.last_actions = [] self.current_legal_actions = [] self.street_dict",
"self.current_hand[self.current_hand.index(old_card)] = new_card self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard = False break",
"self.big_blind = int(bb) # self pre-flop stats self.pfr = 0",
"action: if self.name in action: if self.button: self.has_four_bet = True",
"stats self.pfr = 0 self.vpip = 0 self.three_bet = 0",
"= 'TURNRIVER' elif self.current_game_state == 'TURNRIVER': if self.street_dict['5'] > 0:",
"self.current_legal_actions = [] for i in range(num_legal_actions): self.current_legal_actions.append(data_list[index + i])",
"True else: if self.name in action: self.pfr += 1 self.vpip",
"Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 + num_board_cards num_last_actions = int(data_list[index]) index",
"'PREFLOP' self.board_cards = [] self.last_actions = [] self.current_legal_actions = []",
"self.opponent_has_two_bet = True elif round_num == 2: if self.button: if",
"sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if action == 'CALL': for last_action",
"self.street_dict['5'] == 0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet",
"in last_action: sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True return",
"break elif round_num == 2: for action in current_last_actions: if",
"self.opponent_fold_c_bet += 1 self.num_wins += 1 else: if 'FOLD' in",
"= False self.time_bank = 0.0 self.opc = 0 def new_hand(self,",
"in action: if self.name in action: self.vpip += 1 else:",
"i]) def legal_action(self, action): for legal_action in self.current_legal_actions: if action",
"board_cards.append(Card.new(board_card)) hand = [] for card in self.current_hand: hand.append(Card.new(card)) self.hand_score",
"self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_two_bet = True elif",
"+= 1 self.opponent_vpip += 1 self.opponent_has_two_bet = True elif round_num",
"= True elif round_num == 4: for action in current_last_actions:",
"1 else: self.opponent_c_bet += 1 break elif round_num == 2:",
"1: for action in current_last_actions: if 'BET' in action: if",
"= False self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet =",
"False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'FLOPTURN'",
"True elif round_num == 4: for action in current_last_actions: if",
"break elif self.current_game_state == 'POSTRIVER': round_num = self.street_dict['5'] if round_num",
"in action: self.opponent_c_bet += 1 break elif round_num == 3:",
"Hand from deuces.deuces import Card, Evaluator class GameData: def __init__(self,",
"def get_action(self, data_list): self.current_pot_size = int(data_list[1]) self.opc = self.starting_stack_size -",
"0 self.showdown_win = 0 self.double_barrel = 0 self.discarded_card = None",
"False self.opponent_has_four_bet = False self.street_dict = {'0': 0, '3': 0,",
"'RAISE' in last_action and self.name in last_action: self.opponent_fold_pfr += 1",
"self.num_wins += 1 elif self.current_game_state == 'POSTRIVER': for action in",
"self.current_game_state == 'POSTRIVER': for action in current_last_actions: if 'WIN' in",
"self.aggression_factor = False self.discarded_card = None def get_action(self, data_list): self.current_pot_size",
"== 'POSTRIVER': for action in current_last_actions: if 'WIN' in action:",
"# current hand stats self.button = True self.current_pot_size = 0",
"action: if self.name in action: self.num_wins += 1 for last_action",
"= 0 self.big_blind = int(bb) # self pre-flop stats self.pfr",
"False self.has_four_bet = False self.opponent_has_four_bet = False self.has_bet_aggressively = False",
"in current_last_actions: if 'RAISE' in action: if self.name in action:",
"def legal_action(self, action): for legal_action in self.current_legal_actions: if action in",
"self.has_bet_aggressively = False self.current_game_state = 'POSTRIVER' for i in range(num_board_cards):",
"self.opponent_has_two_bet = False self.has_three_bet = False self.opponent_has_three_bet = False self.has_four_bet",
"legal_action: if action == 'BET' or action == 'RAISE': index",
"= True elif round_num == 2: for action in current_last_actions:",
"self.current_game_state == 'PREFLOP': if self.current_pot_size == 4: if self.button: self.vpip",
"1 else: if 'FOLD' in action and self.opponent_name in action:",
"elif self.current_game_state == 'FLOPTURN': round_num = self.street_dict['3'] if round_num ==",
"1 for last_action in current_last_actions: if 'SHOW' in last_action: self.showdown",
"1 else: self.opponent_double_barrel += 1 break index += num_last_actions num_legal_actions",
"self.has_four_bet = False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state",
"int(data_list[index]) index += 1 current_last_actions = [] for i in",
"in action: self.vpip += 1 else: self.opponent_vpip += 1 elif",
"'3': 0, '4': 0, '5': 0} self.has_two_bet = False self.opponent_has_two_bet",
"'4': 0, '5': 0} self.has_two_bet = False self.opponent_has_two_bet = False",
"current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index + i])",
"action: if self.name in action: self.vpip += 1 else: self.opponent_vpip",
"for i in range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if self.discard:",
"hand stats self.button = True self.current_pot_size = 0 self.current_hand =",
"i in range(num_board_cards): board_card = data_list[3 + i] if board_card",
"elif self.current_game_state == 'POSTRIVER': round_num = self.street_dict['5'] if round_num ==",
"0 self.three_bet = 0 self.fold_big_bet = 0 # opponent pre-flop",
"get_action(self, data_list): self.current_pot_size = int(data_list[1]) self.opc = self.starting_stack_size - self.current_pot_size",
"in action: if self.name in action: self.c_bet += 1 else:",
"in action and self.name in action: old_card = action[8:10] new_card",
"self.board_cards.append(data_list[3 + i]) if num_board_cards > 0: board_cards = []",
"self.has_called = False self.opponent_has_called = False self.has_two_bet = False self.opponent_has_two_bet",
"last_action in current_last_actions: if 'RAISE' in last_action and self.name in",
"> 0 and self.street_dict['5'] == 0: self.has_two_bet = False self.opponent_has_two_bet",
"self.last_actions[-1]: if 'RAISE' in last_action and self.opponent_name in last_action: sub",
"+= num_last_actions num_legal_actions = int(data_list[index]) index += 1 self.current_legal_actions =",
"round_num == 3: if self.name in action: self.pfr += 1",
"self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_three_bet = True else:",
"True self.current_pot_size = 0 self.current_hand = [] self.current_hand_strength = 0.0",
"self.opponent_vpip += 1 elif self.current_game_state == 'FLOPTURN': round_num = self.street_dict['3']",
"= [data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards",
"action: self.has_two_bet = True else: if self.button: self.opponent_has_three_bet = True",
"= True else: if self.button: self.opponent_has_three_bet = True else: self.opponent_has_two_bet",
"last_action and self.name in last_action: self.opponent_fold_c_bet += 1 self.num_wins +=",
"self.current_game_state == 'TURNRIVER': round_num = self.street_dict['4'] if round_num == 1:",
"Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 + num_board_cards",
"self.opponent_fold_three_bet += 1 self.num_wins += 1 elif self.current_game_state == 'FLOPTURN':",
"1 if self.current_game_state == 'PREFLOP': if self.street_dict['3'] > 0 and",
"0 self.opponent_three_bet = 0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet = 0",
"None # opponent post-flop stats self.opponent_c_bet = 0 self.opponent_fold_c_bet =",
"False self.has_bet_aggressively = False self.current_game_state = 'FLOPTURN' self.num_flop += 1",
"in current_last_actions: if 'RAISE' in action: round_num = self.street_dict['0'] if",
"in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP': for action in",
"[int(sub[:index]), int(sub[index+1:])] if action == 'CALL': for last_action in self.last_actions[-1]:",
"in action: if self.button: self.has_four_bet = True else: self.has_three_bet =",
"= 0 self.discarded_card = None # opponent post-flop stats self.opponent_c_bet",
"self.c_bet += 1 else: self.opponent_c_bet += 1 break elif round_num",
"self.street_dict['3'] > 0 and self.street_dict['4'] == 0: self.has_two_bet = False",
"action): for legal_action in self.current_legal_actions: if action in legal_action: if",
"self.three_bet = 0 self.fold_big_bet = 0 # opponent pre-flop stats",
"1: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_two_bet = True",
"'PREFLOP': for action in current_last_actions: if 'FOLD' in action and",
"action: if self.name in action: self.double_barrel += 1 else: self.opponent_double_barrel",
"0 self.c_bet = 0 self.showdown_win = 0 self.double_barrel = 0",
"Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards = [] self.last_actions = []",
"board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 + num_board_cards num_last_actions",
"self.starting_stack_size = int(stack_size) self.num_hands = 0 self.num_wins = 0 self.num_flop",
"== 4: if self.button: self.vpip += 1 self.has_called = True",
"'RAISE' in action: round_num = self.street_dict['0'] if round_num == 1:",
"self.street_dict = {'0': 0, '3': 0, '4': 0, '5': 0}",
"self.name in last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 elif",
"self.button = True else: self.button = False self.current_hand = [data_list[3],",
"1 self.vpip += 1 elif 'CALL' in action: if self.name",
"data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards = []",
"= Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 +",
"self.street_dict['4'] if round_num == 1: self.discard = True for action",
"1 self.opponent_has_three_bet = True else: if self.name in action: self.pfr",
"if self.name in action: self.c_bet += 1 else: self.opponent_c_bet +=",
"legal_action in self.current_legal_actions: if action in legal_action: if action ==",
"else: self.has_three_bet = True break elif self.current_game_state == 'POSTRIVER': round_num",
"in self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score))",
"self.opponent_c_bet += 1 break elif round_num == 2: for action",
"self.has_three_bet = True break elif self.current_game_state == 'TURNRIVER': round_num =",
"# self pre-flop stats self.pfr = 0 self.vpip = 0",
"if 'RAISE' in action: if self.name in action: if self.button:",
"- self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] +=",
"self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index = 3 + num_board_cards num_last_actions =",
"float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if self.current_game_state ==",
"self.opponent_vpip += 1 self.opponent_has_called = True else: for action in",
"+= 1 elif self.current_game_state == 'FLOPTURN': for action in current_last_actions:",
"self.opponent_has_three_bet = True else: self.opponent_has_two_bet = True elif round_num ==",
"== 'PREFLOP': if self.current_pot_size == 4: if self.button: self.vpip +=",
"== 2: if self.button: if self.name in action: self.pfr +=",
"False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'POSTRIVER'",
"action: self.num_wins += 1 for last_action in current_last_actions: if 'SHOW'",
"[] self.current_legal_actions = [] self.street_dict = {'0': 0, '3': 0,",
"= [] self.current_legal_actions = [] self.has_called = False self.opponent_has_called =",
"if \"true\" in self.button: self.button = True else: self.button =",
"1 elif self.current_game_state == 'FLOPTURN': if self.street_dict['4'] > 0 and",
"action in current_last_actions: if 'RAISE' in action: if self.name in",
"self.board_cards: self.board_cards.append(data_list[3 + i]) if num_board_cards > 0: board_cards =",
"'BET' in action: if self.name in action: self.c_bet += 1",
"or action == 'RAISE': index = legal_action.index(':') + 1 sub",
"1 self.has_two_bet = True else: self.opponent_pfr += 1 self.opponent_vpip +=",
"'4': 0, '5': 0} self.discard = False self.has_five_bet = False",
"if self.name in action: self.vpip += 1 else: self.opponent_vpip +=",
"if 'FOLD' in action and self.opponent_name in action: if self.button:",
"last_action and self.opponent_name in last_action: sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')])",
"in last_action: self.opponent_fold_pfr += 1 if self.has_three_bet and not self.has_four_bet:",
"self.aggression_factor = False self.showdown = 0 self.c_bet = 0 self.showdown_win",
"self.opponent_has_called = True else: for action in current_last_actions: if 'RAISE'",
"action == 'CALL': for last_action in self.last_actions[-1]: if 'RAISE' in",
"in action: self.double_barrel += 1 else: self.opponent_double_barrel += 1 break",
"0.0 self.hand_class = '' self.hand_score = 0 self.current_game_state = ''",
"= 'FLOPTURN' self.num_flop += 1 elif self.current_game_state == 'FLOPTURN': if",
"else: self.opponent_has_two_bet = True elif round_num == 4: for action",
"round_num = self.street_dict['4'] if round_num == 1: self.discard = True",
"True elif round_num == 3: if self.name in action: self.pfr",
"self.opc = self.starting_stack_size - self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards =",
"action: self.vpip += 1 else: self.opponent_vpip += 1 elif self.current_game_state",
"action and self.opponent_name in action: if self.button: for last_action in",
"+= 1 self.vpip += 1 self.has_two_bet = True else: self.opponent_pfr",
"self.current_legal_actions: if action in legal_action: if action == 'BET' or",
"for last_action in current_last_actions: if 'RAISE' in last_action and self.name",
"else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_three_bet = True",
"Evaluator class GameData: def __init__(self, name, opponent_name, stack_size, bb): #",
"bb): # match stats self.name = name self.opponent_name = opponent_name",
"in action: self.pfr += 1 self.vpip += 1 elif 'CALL'",
"if round_num == 1: self.discard = True elif round_num ==",
"else: if self.button: self.opponent_has_three_bet = True else: self.opponent_has_two_bet = True",
"= [] for i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state ==",
"= [] for i in range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions)",
"= Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards = [] self.last_actions =",
"'PREFLOP': if self.street_dict['3'] > 0 and self.street_dict['4'] == 0: self.has_two_bet",
"self.name in action: self.c_bet += 1 else: self.opponent_c_bet += 1",
"self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 elif self.current_game_state ==",
"= False self.has_five_bet = False self.has_bet_aggressively = False self.time_bank =",
"= 0 self.opponent_three_bet = 0 self.opponent_fold_pfr = 0 self.opponent_fold_three_bet =",
"0 self.opponent_vpip = 0 self.opponent_three_bet = 0 self.opponent_fold_pfr = 0",
"if self.current_game_state == 'PREFLOP': if self.current_pot_size == 4: if self.button:",
"self.num_flop = 0 self.big_blind = int(bb) # self pre-flop stats",
"= True else: for action in current_last_actions: if 'RAISE' in",
"self.discard = True elif round_num == 2: for action in",
"True for action in current_last_actions: if 'BET' in action: if",
"= last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True return None def hand_over(self,",
"if self.button: if self.name in action: self.pfr += 1 self.vpip",
"self.name = name self.opponent_name = opponent_name self.starting_stack_size = int(stack_size) self.num_hands",
"= True else: self.button = False self.current_hand = [data_list[3], data_list[4]]",
"True else: self.has_three_bet = True break elif self.current_game_state == 'POSTRIVER':",
"name self.opponent_name = opponent_name self.starting_stack_size = int(stack_size) self.num_hands = 0",
"== 'FLOPTURN': for action in current_last_actions: if self.button: if 'FOLD'",
"0 self.double_barrel = 0 self.discarded_card = None # opponent post-flop",
"self.discarded_card = None def get_action(self, data_list): self.current_pot_size = int(data_list[1]) self.opc",
"self.time_bank = 0.0 self.opc = 0 def new_hand(self, data_list): self.num_hands",
"import Card, Evaluator class GameData: def __init__(self, name, opponent_name, stack_size,",
"1 self.vpip += 1 self.has_two_bet = True else: self.opponent_pfr +=",
"4: for action in current_last_actions: if 'RAISE' in action: if",
"0 self.current_hand = [] self.current_hand_strength = 0.0 self.hand_class = ''",
"= [] self.last_actions = [] self.current_legal_actions = [] self.has_called =",
"self.last_actions.append(current_last_actions) if self.discard: for action in current_last_actions: if 'DISCARD' in",
"True break elif self.current_game_state == 'TURNRIVER': round_num = self.street_dict['4'] if",
"self.current_game_state = 'POSTRIVER' for i in range(num_board_cards): board_card = data_list[3",
"in range(num_last_actions): current_last_actions.append(data_list[index + i]) self.last_actions.append(current_last_actions) if self.discard: for action",
"= True else: if self.name in action: self.pfr += 1",
"'RAISE' in action: if self.name in action: if self.button: self.has_four_bet",
"self.name in action: self.has_two_bet = True else: if self.button: self.opponent_has_three_bet",
"= False self.current_game_state = 'POSTRIVER' for i in range(num_board_cards): board_card",
"range(num_legal_actions): self.current_legal_actions.append(data_list[index + i]) def legal_action(self, action): for legal_action in",
"= self.street_dict['4'] if round_num == 1: self.discard = True for",
"== 'CALL': for last_action in self.last_actions[-1]: if 'RAISE' in last_action",
"self.current_game_state == 'FLOPTURN': for action in current_last_actions: if self.button: if",
"else: if self.name in action: self.pfr += 1 self.vpip +=",
"= {'0': 0, '3': 0, '4': 0, '5': 0} self.discard",
"for action in current_last_actions: if 'RAISE' in action: if self.name",
"import HandRankings as Hand from deuces.deuces import Card, Evaluator class",
"= 0 self.num_wins = 0 self.num_flop = 0 self.big_blind =",
"self.opponent_c_bet = 0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel = 0 #",
"num_board_cards num_last_actions = int(data_list[index]) index += 1 current_last_actions = []",
"= True elif round_num == 2: if self.button: if self.name",
"[] self.last_actions = [] self.current_legal_actions = [] self.has_called = False",
"if 'BET' in action: self.opponent_c_bet += 1 break elif round_num",
"round_num == 1: for action in current_last_actions: if 'BET' in",
"self.street_dict['4'] == 0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet",
"for legal_action in self.current_legal_actions: if action in legal_action: if action",
"self.opponent_has_three_bet = False self.has_four_bet = False self.opponent_has_four_bet = False self.street_dict",
"3: if self.name in action: self.pfr += 1 self.vpip +=",
"action: self.double_barrel += 1 else: self.opponent_double_barrel += 1 break index",
"= legal_action[index:] index = sub.index(':') return [int(sub[:index]), int(sub[index+1:])] if action",
"= False self.has_bet_aggressively = False self.current_game_state = 'POSTRIVER' for i",
"self.pfr += 1 self.vpip += 1 self.has_two_bet = True else:",
"in range(num_board_cards): board_card = data_list[3 + i] if board_card not",
"else: self.has_three_bet = True break elif self.current_game_state == 'TURNRIVER': round_num",
"'CALL': for last_action in self.last_actions[-1]: if 'RAISE' in last_action and",
"if self.name in action: self.num_wins += 1 for last_action in",
"= {'0': 0, '3': 0, '4': 0, '5': 0} self.has_two_bet",
"+= 1 else: self.opponent_c_bet += 1 break elif round_num ==",
"self.num_wins += 1 else: for last_action in current_last_actions: if 'RAISE'",
"0 self.num_wins = 0 self.num_flop = 0 self.big_blind = int(bb)",
"self.discard = False self.has_five_bet = False self.has_bet_aggressively = False self.time_bank",
"self.last_actions = [] self.current_legal_actions = [] self.has_called = False self.opponent_has_called",
"1 self.num_wins += 1 else: if 'FOLD' in action and",
"self.opponent_vpip += 1 self.opponent_has_three_bet = True else: if self.name in",
"self.button = False self.current_hand = [data_list[3], data_list[4]] self.current_hand_strength = Hand.hand_win_odds(self.current_hand)",
"in action: round_num = self.street_dict['0'] if round_num == 1: self.opponent_pfr",
"False self.has_three_bet = False self.opponent_has_three_bet = False self.has_four_bet = False",
"+= 1 current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index",
"in last_action: self.showdown += 1 self.showdown_win += 1 break break",
"self.discard = True for action in current_last_actions: if 'BET' in",
"def __init__(self, name, opponent_name, stack_size, bb): # match stats self.name",
"if 'WIN' in action: if self.name in action: self.num_wins +=",
"0 # opponent pre-flop stats self.opponent_pfr = 0 self.opponent_vpip =",
"+= 1 self.opponent_has_called = True else: for action in current_last_actions:",
"int(bb) # self pre-flop stats self.pfr = 0 self.vpip =",
"if self.street_dict['4'] > 0 and self.street_dict['5'] == 0: self.has_two_bet =",
"and not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 elif",
"+ i] if board_card not in self.board_cards: self.board_cards.append(data_list[3 + i])",
"self.opponent_vpip += 1 self.opponent_has_two_bet = True elif round_num == 2:",
"self.has_bet_aggressively = False self.current_game_state = 'TURNRIVER' elif self.current_game_state == 'TURNRIVER':",
"in action: if self.name in action: self.has_two_bet = True else:",
"= legal_action.index(':') + 1 sub = legal_action[index:] index = sub.index(':')",
"self.button = True self.current_pot_size = 0 self.current_hand = [] self.current_hand_strength",
"self.c_bet += 1 else: self.opponent_c_bet += 1 elif 'RAISE' in",
"self.opponent_fold_pfr += 1 if self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet +=",
"True elif round_num == 2: if self.button: if self.name in",
"and self.name in last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1",
"> 0: self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet =",
"= Hand.hand_win_odds(self.current_hand) self.discard = False break if self.current_game_state == 'PREFLOP':",
"= self.street_dict['3'] if round_num == 1: self.discard = True elif",
"+= 1 elif 'RAISE' in action: if self.name in action:",
"action: self.c_bet += 1 else: self.opponent_c_bet += 1 break elif",
"= True break elif self.current_game_state == 'POSTRIVER': round_num = self.street_dict['5']",
"in current_last_actions: if 'WIN' in action: if self.name in action:",
"self.discarded_card = None # opponent post-flop stats self.opponent_c_bet = 0",
"self.last_actions[-1]: if 'BET' in last_action and self.name in last_action: self.opponent_fold_c_bet",
"self.button: self.has_four_bet = True else: self.has_three_bet = True break elif",
"if self.discard: for action in current_last_actions: if 'DISCARD' in action",
"'RAISE' in last_action and self.opponent_name in last_action: sub = last_action[last_action.index(':')+1:]",
"self.num_flop += 1 elif self.current_game_state == 'FLOPTURN': if self.street_dict['4'] >",
"int(sub[:sub.index(':')]) return True return None def hand_over(self, data_list): num_board_cards =",
"HandRankings as Hand from deuces.deuces import Card, Evaluator class GameData:",
"0 and self.street_dict['4'] == 0: self.has_two_bet = False self.opponent_has_two_bet =",
"= int(data_list[index]) index += 1 current_last_actions = [] for i",
"self.opponent_has_four_bet = True elif round_num == 3: if self.name in",
"in action: self.c_bet += 1 else: self.opponent_c_bet += 1 elif",
"stats self.button = True self.current_pot_size = 0 self.current_hand = []",
"= True break elif self.current_game_state == 'TURNRIVER': round_num = self.street_dict['4']",
"break elif self.current_game_state == 'TURNRIVER': round_num = self.street_dict['4'] if round_num",
"1 break elif round_num == 2: for action in current_last_actions:",
"= 0 # current hand stats self.button = True self.current_pot_size",
"= 0 self.fold_big_bet = 0 # opponent pre-flop stats self.opponent_pfr",
"+= 1 self.has_three_bet = True else: self.opponent_pfr += 1 self.opponent_vpip",
"self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.current_game_state = 'PREFLOP' self.board_cards = [] self.last_actions",
"self.current_game_state == 'TURNRIVER': if self.street_dict['5'] > 0: self.has_two_bet = False",
"action: self.pfr += 1 self.vpip += 1 self.has_two_bet = True",
"False self.showdown = 0 self.c_bet = 0 self.showdown_win = 0",
"action: self.c_bet += 1 else: self.opponent_c_bet += 1 elif 'RAISE'",
"for last_action in self.last_actions[-1]: if 'RAISE' in last_action and self.opponent_name",
"current_last_actions: if 'BET' in last_action and self.name in last_action: self.opponent_fold_c_bet",
"self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] += 1",
"num_last_actions = data_list[index] current_last_actions = [] for i in range(num_last_actions):",
"'WIN' in action: if self.name in action: self.num_wins += 1",
"1 self.has_called = True else: self.opponent_vpip += 1 self.opponent_has_called =",
"def new_hand(self, data_list): self.num_hands += 1 self.button = data_list[2] if",
"self.button: if self.name in action: self.pfr += 1 self.vpip +=",
"True else: self.has_three_bet = True break elif self.current_game_state == 'TURNRIVER':",
"'RAISE' in action: if self.name in action: self.has_two_bet = True",
"post-flop stats self.aggression_factor = False self.showdown = 0 self.c_bet =",
"data_list[index] current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if",
"in action: old_card = action[8:10] new_card = action[11:13] self.current_hand[self.current_hand.index(old_card)] =",
"'5': 0} self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet =",
"if 'SHOW' in last_action: self.showdown += 1 self.showdown_win += 1",
"self.current_pot_size == 4: if self.button: self.vpip += 1 self.has_called =",
"current_last_actions: if 'BET' in action: self.opponent_c_bet += 1 break elif",
"if self.current_game_state == 'PREFLOP': for action in current_last_actions: if 'FOLD'",
"0 self.current_game_state = '' self.board_cards = [] self.last_actions = []",
"= True for action in current_last_actions: if 'BET' in action:",
"self.board_cards: board_cards.append(Card.new(board_card)) hand = [] for card in self.current_hand: hand.append(Card.new(card))",
"+= 1 self.opponent_has_two_bet = True elif round_num == 2: if",
"range(num_board_cards): board_card = data_list[3 + i] if board_card not in",
"self.current_game_state = 'TURNRIVER' elif self.current_game_state == 'TURNRIVER': if self.street_dict['5'] >",
"False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state = 'TURNRIVER'",
"for i in range(num_board_cards): board_card = data_list[3 + i] if",
"= 0 self.three_bet = 0 self.fold_big_bet = 0 # opponent",
"[] self.street_dict = {'0': 0, '3': 0, '4': 0, '5':",
"for board_card in self.board_cards: board_cards.append(Card.new(board_card)) hand = [] for card",
"False self.street_dict = {'0': 0, '3': 0, '4': 0, '5':",
"+= 1 self.opponent_vpip += 1 self.opponent_has_four_bet = True elif round_num",
"round_num == 1: self.discard = True elif round_num == 2:",
"in action: if self.name in action: self.double_barrel += 1 else:",
"num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if self.current_game_state == 'PREFLOP':",
"= int(data_list[2]) self.street_dict[str(num_board_cards)] += 1 if self.current_game_state == 'PREFLOP': if",
"+= 1 self.has_two_bet = True else: self.opponent_pfr += 1 self.opponent_vpip",
"== 'FLOPTURN': round_num = self.street_dict['3'] if round_num == 1: self.discard",
"self.num_wins += 1 for last_action in current_last_actions: if 'SHOW' in",
"+= 1 self.opponent_has_four_bet = True elif round_num == 3: if",
"and self.street_dict['4'] == 0: self.has_two_bet = False self.opponent_has_two_bet = False",
"True else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_three_bet =",
"self.c_bet = 0 self.showdown_win = 0 self.double_barrel = 0 self.discarded_card",
"self.current_game_state == 'FLOPTURN': if self.street_dict['4'] > 0 and self.street_dict['5'] ==",
"= False self.has_bet_aggressively = False self.aggression_factor = False self.discarded_card =",
"self.button: for last_action in self.last_actions[-1]: if 'RAISE' in last_action and",
"self.current_hand_strength = Hand.hand_win_odds(self.current_hand) self.discard = False break if self.current_game_state ==",
"False self.current_game_state = 'POSTRIVER' for i in range(num_board_cards): board_card =",
"num_legal_actions = int(data_list[index]) index += 1 self.current_legal_actions = [] for",
"self.button = data_list[2] if \"true\" in self.button: self.button = True",
"class GameData: def __init__(self, name, opponent_name, stack_size, bb): # match",
"def hand_over(self, data_list): num_board_cards = data_list[3] index = 4+num_board_cards num_last_actions",
"= False self.aggression_factor = False self.discarded_card = None def get_action(self,",
"stats self.aggression_factor = False self.showdown = 0 self.c_bet = 0",
"True else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_four_bet =",
"if 'BET' in last_action and self.name in last_action: self.opponent_fold_c_bet +=",
"last_action: self.opponent_fold_c_bet += 1 self.num_wins += 1 else: if 'FOLD'",
"+= 1 else: self.opponent_vpip += 1 elif self.current_game_state == 'FLOPTURN':",
"= False self.opponent_has_four_bet = False self.has_bet_aggressively = False self.current_game_state =",
"False self.current_game_state = 'FLOPTURN' self.num_flop += 1 elif self.current_game_state ==",
"self.has_called = True else: self.opponent_vpip += 1 self.opponent_has_called = True",
"= True else: self.opponent_pfr += 1 self.opponent_vpip += 1 self.opponent_has_three_bet",
"False self.current_game_state = 'TURNRIVER' elif self.current_game_state == 'TURNRIVER': if self.street_dict['5']",
"self.has_four_bet = False self.opponent_has_four_bet = False self.street_dict = {'0': 0,",
"+= 1 self.vpip += 1 elif 'CALL' in action: if",
"= '' self.board_cards = [] self.last_actions = [] self.current_legal_actions =",
"break index += num_last_actions num_legal_actions = int(data_list[index]) index += 1",
"hand = [] for card in self.current_hand: hand.append(Card.new(card)) self.hand_score =",
"'POSTRIVER': for action in current_last_actions: if 'WIN' in action: if",
"self.street_dict[str(num_board_cards)] += 1 if self.current_game_state == 'PREFLOP': if self.street_dict['3'] >",
"opponent post-flop stats self.opponent_c_bet = 0 self.opponent_fold_c_bet = 0 self.opponent_double_barrel",
"action: if self.name in action: self.c_bet += 1 else: self.opponent_c_bet",
"action: self.pfr += 1 self.vpip += 1 elif 'CALL' in",
"= 'POSTRIVER' for i in range(num_board_cards): board_card = data_list[3 +",
"self.button: self.vpip += 1 self.has_called = True else: self.opponent_vpip +=",
"in action: if self.name in action: self.num_wins += 1 for",
"action and self.opponent_name in action: for last_action in self.last_actions[-1]: if",
"False self.has_four_bet = False self.opponent_has_four_bet = False self.street_dict = {'0':",
"'FLOPTURN': round_num = self.street_dict['3'] if round_num == 1: self.discard =",
"action and self.name in action: old_card = action[8:10] new_card =",
"last_action in self.last_actions[-1]: if 'RAISE' in last_action and self.name in",
"for action in current_last_actions: if 'BET' in action: if self.name",
"current_last_actions.append(data_list[index+i]) if self.current_game_state == 'PREFLOP': for action in current_last_actions: if",
"current_last_actions: if 'BET' in action: if self.name in action: self.double_barrel",
"> 0 and self.street_dict['4'] == 0: self.has_two_bet = False self.opponent_has_two_bet",
"1 break elif round_num == 3: for action in current_last_actions:",
"'5': 0} self.discard = False self.has_five_bet = False self.has_bet_aggressively =",
"and not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins += 1 else:",
"self.opponent_name in last_action: sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return True",
"for action in current_last_actions: if 'DISCARD' in action and self.name",
"if self.current_game_state == 'PREFLOP': if self.street_dict['3'] > 0 and self.street_dict['4']",
"self.opponent_c_bet += 1 elif 'RAISE' in action: if self.name in",
"1 self.has_three_bet = True else: self.opponent_pfr += 1 self.opponent_vpip +=",
"0 self.vpip = 0 self.three_bet = 0 self.fold_big_bet = 0",
"if action == 'CALL': for last_action in self.last_actions[-1]: if 'RAISE'",
"1 if self.has_three_bet and not self.has_four_bet: self.opponent_fold_three_bet += 1 self.num_wins",
"1 break index += num_last_actions num_legal_actions = int(data_list[index]) index +=",
"and self.opponent_name in last_action: sub = last_action[last_action.index(':')+1:] return int(sub[:sub.index(':')]) return",
"# self post-flop stats self.aggression_factor = False self.showdown = 0",
"1 self.opponent_vpip += 1 self.opponent_has_two_bet = True elif round_num ==",
"current_last_actions = [] for i in range(num_last_actions): current_last_actions.append(data_list[index+i]) if self.current_game_state",
"= 0 self.num_flop = 0 self.big_blind = int(bb) # self",
"'TURNRIVER': if self.street_dict['5'] > 0: self.has_two_bet = False self.opponent_has_two_bet =",
"last_action in current_last_actions: if 'BET' in last_action and self.name in",
"self.starting_stack_size - self.current_pot_size self.time_bank = float(data_list[-1]) num_board_cards = int(data_list[2]) self.street_dict[str(num_board_cards)]",
"self.opponent_has_three_bet = True else: if self.name in action: self.pfr +=",
"+= 1 elif self.current_game_state == 'FLOPTURN': round_num = self.street_dict['3'] if",
"round_num == 2: for action in current_last_actions: if 'BET' in",
"= name self.opponent_name = opponent_name self.starting_stack_size = int(stack_size) self.num_hands =",
"in action: if self.button: for last_action in self.last_actions[-1]: if 'RAISE'",
"if 'BET' in action: if self.name in action: self.c_bet +=",
"self.pfr += 1 self.vpip += 1 elif 'CALL' in action:",
"True else: for action in current_last_actions: if 'RAISE' in action:",
"= False self.opponent_has_four_bet = False self.street_dict = {'0': 0, '3':",
"0, '5': 0} self.has_two_bet = False self.opponent_has_two_bet = False self.has_three_bet",
"None def hand_over(self, data_list): num_board_cards = data_list[3] index = 4+num_board_cards",
"self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class = Evaluator().class_to_string(Evaluator().get_rank_class(self.hand_score)) index",
"card in self.current_hand: hand.append(Card.new(card)) self.hand_score = Evaluator().evaluate(hand, board_cards) self.hand_class =",
"num_last_actions = int(data_list[index]) index += 1 current_last_actions = [] for",
"self post-flop stats self.aggression_factor = False self.showdown = 0 self.c_bet",
"[] self.has_called = False self.opponent_has_called = False self.has_two_bet = False",
"elif round_num == 4: for action in current_last_actions: if 'RAISE'",
"self.name in action: self.pfr += 1 self.vpip += 1 elif",
"self.current_game_state = '' self.board_cards = [] self.last_actions = [] self.current_legal_actions",
"self.opponent_double_barrel += 1 break index += num_last_actions num_legal_actions = int(data_list[index])",
"+ 1 sub = legal_action[index:] index = sub.index(':') return [int(sub[:index]),",
"= data_list[2] if \"true\" in self.button: self.button = True else:",
"if 'RAISE' in last_action and self.opponent_name in last_action: sub =",
"index = 4+num_board_cards num_last_actions = data_list[index] current_last_actions = [] for",
"if self.button: if 'FOLD' in action and self.opponent_name in action:"
] |
[
"return (self.deadline - timezone.now()).total_seconds() def state(self): if self.done: return 'Done'",
"self.seconds_left() > 0: return 'Todo' else: return 'Exceeded' class Meta:",
"def seconds_left(self): return (self.deadline - timezone.now()).total_seconds() def state(self): if self.done:",
"def state(self): if self.done: return 'Done' elif self.seconds_left() > 0:",
"0: return 'Todo' else: return 'Exceeded' class Meta: ordering =",
"import timezone class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64)",
"seconds_left(self): return (self.deadline - timezone.now()).total_seconds() def state(self): if self.done: return",
"= models.CharField(max_length=64) detail = models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user =",
"detail = models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE)",
"self.title def seconds_left(self): return (self.deadline - timezone.now()).total_seconds() def state(self): if",
"- timezone.now()).total_seconds() def state(self): if self.done: return 'Done' elif self.seconds_left()",
"User from django.utils import timezone class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True)",
"title = models.CharField(max_length=64) detail = models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user",
"done = models.BooleanField(default=False) def __str__(self): return self.title def seconds_left(self): return",
"models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False) def __str__(self):",
"Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail = models.TextField(blank=True)",
"import models from django.contrib.auth.models import User from django.utils import timezone",
"models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False) def __str__(self): return self.title def",
"= models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) done",
"deadline = models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False)",
"elif self.seconds_left() > 0: return 'Todo' else: return 'Exceeded' class",
"on_delete=models.CASCADE) done = models.BooleanField(default=False) def __str__(self): return self.title def seconds_left(self):",
"= models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail = models.TextField(blank=True) deadline =",
"self.done: return 'Done' elif self.seconds_left() > 0: return 'Todo' else:",
"django.contrib.auth.models import User from django.utils import timezone class Todo(models.Model): time_add",
"def __str__(self): return self.title def seconds_left(self): return (self.deadline - timezone.now()).total_seconds()",
"models from django.contrib.auth.models import User from django.utils import timezone class",
"django.utils import timezone class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title =",
"from django.contrib.auth.models import User from django.utils import timezone class Todo(models.Model):",
"(self.deadline - timezone.now()).total_seconds() def state(self): if self.done: return 'Done' elif",
"return 'Todo' else: return 'Exceeded' class Meta: ordering = ['deadline']",
"state(self): if self.done: return 'Done' elif self.seconds_left() > 0: return",
"from django.utils import timezone class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title",
"models.BooleanField(default=False) def __str__(self): return self.title def seconds_left(self): return (self.deadline -",
"class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail =",
"user = models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False) def __str__(self): return",
"django.db import models from django.contrib.auth.models import User from django.utils import",
"__str__(self): return self.title def seconds_left(self): return (self.deadline - timezone.now()).total_seconds() def",
"= models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False) def __str__(self): return self.title",
"if self.done: return 'Done' elif self.seconds_left() > 0: return 'Todo'",
"= models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) done = models.BooleanField(default=False) def",
"timezone.now()).total_seconds() def state(self): if self.done: return 'Done' elif self.seconds_left() >",
"timezone class Todo(models.Model): time_add = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail",
"from django.db import models from django.contrib.auth.models import User from django.utils",
"time_add = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail = models.TextField(blank=True) deadline",
"models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=64) detail = models.TextField(blank=True) deadline = models.DateTimeField(blank=True)",
"'Done' elif self.seconds_left() > 0: return 'Todo' else: return 'Exceeded'",
"> 0: return 'Todo' else: return 'Exceeded' class Meta: ordering",
"return 'Done' elif self.seconds_left() > 0: return 'Todo' else: return",
"= models.BooleanField(default=False) def __str__(self): return self.title def seconds_left(self): return (self.deadline",
"return self.title def seconds_left(self): return (self.deadline - timezone.now()).total_seconds() def state(self):",
"import User from django.utils import timezone class Todo(models.Model): time_add =",
"models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user = models.ForeignKey(User, on_delete=models.CASCADE) done =",
"models.CharField(max_length=64) detail = models.TextField(blank=True) deadline = models.DateTimeField(blank=True) user = models.ForeignKey(User,"
] |
[
"active ui card layout.state = { \"active_ui\": None, } #",
"color map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0,",
"mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx]",
"LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset ==",
"Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step)",
"Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field",
"# Representation Callbacks # ----------------------------------------------------------------------------- def update_representation(actor, mode): property =",
"3}, ], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\",",
"\"[$event]\"), ) # ----------------------------------------------------------------------------- # GUI Cards # ----------------------------------------------------------------------------- def",
"title, classes=\"grey lighten-1 py-1 grey--text text--darken-3\", style=\"user-select: none; cursor: pointer\",",
"{\"text\": \"Greyscale\", \"value\": 2}, {\"text\": \"Inv Greyscale\", \"value\": 3}, ],",
"{\"text\": \"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3}, ], ),",
"mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow color map mesh_lut =",
"for field in fields: field_arrays, association = field for i",
"vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour =",
"else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes = vtkCubeAxesActor()",
"def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view() # ----------------------------------------------------------------------------- # ColorBy",
"SinglePageWithDrawer from trame.html import vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel import",
"# noqa # Required for remote rendering factory initialization, not",
"Contour: ContourBy default array contour_value = 0.5 * (default_max +",
"layout.content.children[0].children[0] = html_view layout.flush_content() # Update View update_view() # -----------------------------------------------------------------------------",
"with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True,",
"Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\")",
") # State use to track active ui card layout.state",
"SurfaceWithEdges = 3 class LookupTable: Rainbow = 0 Inverted_Rainbow =",
"noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants # -----------------------------------------------------------------------------",
"def use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow:",
"color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx]",
"dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\",",
"# ----------------------------------------------------------------------------- def color_by_array(actor, array): _min, _max = array.get(\"range\") mapper",
"property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\")",
"mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True)",
"# Cube Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes:",
"layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar components",
"----------------------------------------------------------------------------- # Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs):",
"0.01 * (contour_max - contour_min) contour_value = 0.5 * (contour_max",
"for i in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range = array.GetRange()",
"\"1\", \"visible\": 1, \"name\": \"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change,",
"v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0}, {\"text\":",
"1}, {\"text\": \"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3}, ],",
"reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field information",
"list(array_range), \"type\": association, } ) default_array = dataset_arrays[0] default_min, default_max",
"array.get(\"text\")) contour.SetValue(0, contour_value) # Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max)",
"from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation",
"**kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() #",
"Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\", \"value\": 2}, {\"text\": \"Inv Greyscale\",",
") default_array = dataset_arrays[0] default_min, default_max = default_array.get(\"range\") # Mesh",
"update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view() # -----------------------------------------------------------------------------",
"* (contour_max + contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0,",
"components drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content:",
"# Update layout layout.content.children[0].children[0] = html_view layout.flush_content() # Update View",
"= 0.01 * (contour_max - contour_min) contour_value = 0.5 *",
"\"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\", \"visible\": 1, \"name\": \"Contour\"},",
"vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper, vtkRenderer,",
"on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\")",
"Update View update_view() # ----------------------------------------------------------------------------- # Representation Callbacks # -----------------------------------------------------------------------------",
"Greyscale = 2 Inverted_Greyscale = 3 # ----------------------------------------------------------------------------- # VTK",
"vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) #",
"dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\",",
"lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0)",
"Views # ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,))",
"pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content: # content components vuetify.VContainer(",
"Greyscale\", \"value\": 3}, ], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", )",
"----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity,",
"on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\",",
"( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) # Required for",
"mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges:",
"cursor: pointer\", hide_details=True, dense=True, ) content = vuetify.VCardText(classes=\"py-2\") return content",
"update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view() # ----------------------------------------------------------------------------- # Pipeline Widget",
"necessary for # local rendering, but doesn't hurt to include",
"default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True)",
"update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view() # ----------------------------------------------------------------------------- # ColorBy Callbacks",
"0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh: Color by",
"= field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append( { \"text\": array.GetName(), \"value\":",
"vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes",
"(reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in fields: field_arrays,",
"mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array =",
"default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply",
"contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor)",
"\"visible\": 1, \"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\", \"visible\": 1,",
"vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in fields: field_arrays, association = field",
"2 Inverted_Greyscale = 3 # ----------------------------------------------------------------------------- # VTK pipeline #",
"# Contour: Apply rainbow color map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666,",
"lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def",
"items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\": \"Inv Rainbow\",",
"default_array.get(\"range\") # Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor()",
"from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa # Required for remote",
"change, update_state from trame.layouts import SinglePageWithDrawer from trame.html import vtk,",
"layout.flush_content() # Update View update_view() # ----------------------------------------------------------------------------- # Representation Callbacks",
"ColorMap Callbacks # ----------------------------------------------------------------------------- def use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable()",
"elif _id == \"2\": # Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\",",
"with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [ {\"text\":",
"Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") ==",
"\"2\": # Contour contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- # GUI Toolbar",
"3}, ], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\",",
"contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow color map contour_lut = contour_mapper.GetLookupTable()",
"(reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in fields: field_arrays, association =",
"class Representation: Points = 0 Wireframe = 1 Surface =",
"# Contour: Color by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if",
"default_array.get(\"text\") ) contour.SetValue(0, contour_value) # Contour: Setup default representation to",
"from trame.html import vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel import vtkDataObject",
"\"2\": # Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\") # Visibility",
"vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import",
"== \"2\": # Contour contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- # GUI",
"property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def",
"**kwargs): update_representation(contour_actor, contour_representation) update_view() # ----------------------------------------------------------------------------- # ColorBy Callbacks #",
"Representation Callbacks # ----------------------------------------------------------------------------- def update_representation(actor, mode): property = actor.GetProperty()",
"3}, ], ), label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with",
"interactive_ratio=(1,)) html_view = local_view # ----------------------------------------------------------------------------- # Callbacks # -----------------------------------------------------------------------------",
"== Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor,",
"def visibility_change(event): _id = event[\"id\"] _visibility = event[\"visible\"] if _id",
"to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow color",
"\"value\": 3}, ], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider(",
"layout.state = { \"active_ui\": None, } # ----------------------------------------------------------------------------- # Main",
"\"type\": association, } ) default_array = dataset_arrays[0] default_min, default_max =",
"= vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read",
"= mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() #",
"range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append( { \"text\":",
"if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) #",
"import os from trame import change, update_state from trame.layouts import",
"1.0) contour_lut.Build() # Contour: Color by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max)",
"map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0)",
"contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes)",
"cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- #",
"classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\",",
"classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\",",
"CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants # ----------------------------------------------------------------------------- class",
"0, 0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value) # Contour: Setup",
"lighten-1 py-1 grey--text text--darken-3\", style=\"user-select: none; cursor: pointer\", hide_details=True, dense=True,",
"vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\",",
"contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour: Color",
"0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value) # Contour: Setup default",
"Color by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") ==",
"Change def actives_change(ids): _id = ids[0] if _id == \"1\":",
"vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content: # content components vuetify.VContainer( fluid=True,",
"State use to track active ui card layout.state = {",
"array contour_value = 0.5 * (default_max + default_min) contour.SetInputArrayToProcess( 0,",
"Toolbar Buttons # ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\",",
"\"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif _id == \"2\": # Contour",
"= [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in",
"label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0},",
"components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view], ) # State use",
"= event[\"visible\"] if _id == \"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif",
"vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants",
"lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Greyscale:",
"color_by_array(actor, array): _min, _max = array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\"))",
"ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\":",
"\"Inv Greyscale\", \"value\": 3}, ], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\",",
") with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [",
"vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True,",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min),",
"vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup",
"association, } ) default_array = dataset_arrays[0] default_min, default_max = default_array.get(\"range\")",
"contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) # Update View",
"# content components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view], ) #",
"def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): #",
"LookupTable: Rainbow = 0 Inverted_Rainbow = 1 Greyscale = 2",
"325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content: # content components",
"local_view = vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view",
"in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append( {",
"----------------------------------------------------------------------------- # Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs):",
"local_view else: html_view = remote_view # Update layout layout.content.children[0].children[0] =",
"property.SetPointSize(5) property.EdgeVisibilityOff() elif mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif",
"@change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view() # ----------------------------------------------------------------------------- #",
"it import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # -----------------------------------------------------------------------------",
"but doesn't hurt to include it import vtkmodules.vtkRenderingOpenGL2 # noqa",
"1.0) elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0,",
"v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True),",
"vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor,",
"# Switch html_view global html_view if local_vs_remote: html_view = local_view",
"Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1)",
"to include it import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__))",
") vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, )",
"with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI Pipelines Widget",
"# Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort())",
"if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True)",
"= 1 Greyscale = 2 Inverted_Greyscale = 3 # -----------------------------------------------------------------------------",
"contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) # Update",
"ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True,",
"ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\",",
"toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer as drawer:",
"\"parent\": \"0\", \"visible\": 1, \"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\",",
"cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame Views",
"[ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\": \"Inv Rainbow\", \"value\": 1},",
"v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0}, {\"text\":",
"2 SurfaceWithEdges = 3 class LookupTable: Rainbow = 0 Inverted_Rainbow",
"lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view()",
"update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) # Update View update_view() @change(\"contour_value\") def",
"# ----------------------------------------------------------------------------- # Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() #",
"def actives_change(ids): _id = ids[0] if _id == \"1\": #",
"Extract Array/Field information dataset_arrays = [] fields = [ (reader.GetOutput().GetPointData(),",
"outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=(",
"\"value\": i, \"range\": list(array_range), \"type\": association, } ) default_array =",
"0 Inverted_Rainbow = 1 Greyscale = 2 Inverted_Greyscale = 3",
"visibility_change=(visibility_change, \"[$event]\"), ) # ----------------------------------------------------------------------------- # GUI Cards # -----------------------------------------------------------------------------",
"import change, update_state from trame.layouts import SinglePageWithDrawer from trame.html import",
"= 2 Inverted_Greyscale = 3 # ----------------------------------------------------------------------------- # VTK pipeline",
"} ) default_array = dataset_arrays[0] default_min, default_max = default_array.get(\"range\") #",
"= 0.5 * (default_max + default_min) contour.SetInputArrayToProcess( 0, 0, 0,",
"# GUI Cards # ----------------------------------------------------------------------------- def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui",
"\"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) # -----------------------------------------------------------------------------",
"0.01 * (default_max - default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, )",
") contour.SetValue(0, contour_value) # Contour: Setup default representation to surface",
"(default_max - default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\",",
"renderer.AddActor(mesh_actor) # Mesh: Setup default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1)",
"vuetify, widgets from vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter",
"array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() # ----------------------------------------------------------------------------- # ColorMap",
"renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor()",
"renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader",
"**kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset)",
"_id = ids[0] if _id == \"1\": # Mesh update_state(\"active_ui\",",
"mesh_actor.SetVisibility(_visibility) elif _id == \"2\": # Contour contour_actor.SetVisibility(_visibility) update_view() #",
"{ \"text\": array.GetName(), \"value\": i, \"range\": list(array_range), \"type\": association, }",
"# Constants # ----------------------------------------------------------------------------- class Representation: Points = 0 Wireframe",
"----------------------------------------------------------------------------- # Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() # -----------------------------------------------------------------------------",
"\"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) # ----------------------------------------------------------------------------- # GUI Cards #",
"contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy default array contour_value = 0.5",
"1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0,",
"drawer: # drawer components drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card()",
"min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) def contour_card():",
"mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor,",
"Contour contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- # GUI Toolbar Buttons #",
"standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, )",
"{\"text\": \"Wireframe\", \"value\": 1}, {\"text\": \"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\",",
"vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\",",
"= default_array.get(\"range\") # Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor =",
"update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def",
"for interacter factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa",
"contour_step) # Update View update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0,",
"default_max = default_array.get(\"range\") # Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor",
") with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\",",
"----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\")",
"dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1,",
"vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from",
"Points = 0 Wireframe = 1 Surface = 2 SurfaceWithEdges",
"Callbacks # ----------------------------------------------------------------------------- def update_representation(actor, mode): property = actor.GetProperty() if",
"mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS:",
"return content def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface),",
"classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\",",
"# trame Views # ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view =",
"layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons()",
"lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666)",
"update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view()",
"vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True,",
"mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh: Color by default",
"use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow: lut.SetHueRange(0.666,",
"none; cursor: pointer\", hide_details=True, dense=True, ) content = vuetify.VCardText(classes=\"py-2\") return",
"as drawer: # drawer components drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\")",
"vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\",",
"{\"text\": \"Points\", \"value\": 0}, {\"text\": \"Wireframe\", \"value\": 1}, {\"text\": \"Surface\",",
"mode): property = actor.GetProperty() if mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5)",
"GUI Toolbar Buttons # ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True),",
"click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI Pipelines Widget # -----------------------------------------------------------------------------",
"dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\",",
"----------------------------------------------------------------------------- # VTK pipeline # ----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow",
"vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from",
"True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\",",
"\"Wireframe\", \"value\": 1}, {\"text\": \"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\":",
"event[\"id\"] _visibility = event[\"visible\"] if _id == \"1\": # Mesh",
"default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 * (default_max - default_min)), label=\"Value\",",
"html_view if local_vs_remote: html_view = local_view else: html_view = remote_view",
"@change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view()",
"\"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\", \"visible\": 1, \"name\": \"Contour\"}, ],",
"# ----------------------------------------------------------------------------- class Representation: Points = 0 Wireframe = 1",
"contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- # Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\")",
"outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\",",
"Surface = 2 SurfaceWithEdges = 3 class LookupTable: Rainbow =",
"Apply rainbow color map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0,",
"0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0,",
"if local_vs_remote: html_view = local_view else: html_view = remote_view #",
"# Contour: ContourBy default array contour_value = 0.5 * (default_max",
"# ----------------------------------------------------------------------------- def update_representation(actor, mode): property = actor.GetProperty() if mode",
"== \"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif _id == \"2\": #",
"= vuetify.VCardText(classes=\"py-2\") return content def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect(",
"include it import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) #",
"= field for i in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range",
"1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0,",
"mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData()",
"dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\") contour_step = 0.01 * (contour_max",
"(contour_max + contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value)",
"LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset ==",
"association = field for i in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i)",
"array = field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append( { \"text\": array.GetName(),",
"vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import",
"\"pipeline\", [ {\"id\": \"1\", \"parent\": \"0\", \"visible\": 1, \"name\": \"Mesh\"},",
"update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\") # Visibility Change def visibility_change(event):",
") with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\",",
"reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field information dataset_arrays = []",
"contour_value) # Contour: Setup default representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1)",
"SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True,",
"v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, )",
"with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\":",
"0.5 * (default_max + default_min) contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"),",
"vuetify.VCardText(classes=\"py-2\") return content def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\",",
"rendering, but doesn't hurt to include it import vtkmodules.vtkRenderingOpenGL2 #",
"**kwargs): # Switch html_view global html_view if local_vs_remote: html_view =",
"@change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs):",
"# Mesh update_state(\"active_ui\", \"mesh\") elif _id == \"2\": # Contour",
"contour.SetValue(0, float(contour_value)) update_view() # ----------------------------------------------------------------------------- # Pipeline Widget Callbacks #",
"----------------------------------------------------------------------------- # GUI Toolbar Buttons # ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox(",
"Pipelines Widget # ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [",
"vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox(",
"from trame import change, update_state from trame.layouts import SinglePageWithDrawer from",
"contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy default",
"Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0}, {\"text\": \"Wireframe\",",
"], ), label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\",",
"import vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor",
"vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) # Required for interacter factory",
"vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True,",
"vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data",
"vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer as drawer: # drawer components",
"----------------------------------------------------------------------------- def update_representation(actor, mode): property = actor.GetProperty() if mode ==",
"0 Wireframe = 1 Surface = 2 SurfaceWithEdges = 3",
"lut = actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0,",
"preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build()",
"contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- # GUI Toolbar Buttons # -----------------------------------------------------------------------------",
"off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\",",
"\"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3}, ], ), label=\"Representation\",",
"classes=\"grey lighten-1 py-1 grey--text text--darken-3\", style=\"user-select: none; cursor: pointer\", hide_details=True,",
"update_view() # ----------------------------------------------------------------------------- # Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def",
"Widget # ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [ {\"id\":",
") vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\":",
"property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff()",
"update_representation(actor, mode): property = actor.GetProperty() if mode == Representation.Points: property.SetRepresentationToPoints()",
"dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect(",
"vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True,",
"1.0) mesh_lut.Build() # Mesh: Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min,",
"fluid=True, classes=\"pa-0 fill-height\", children=[html_view], ) # State use to track",
"vtkCubeAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor,",
"field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append( { \"text\": array.GetName(), \"value\": i,",
"mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs):",
"hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [ {\"text\":",
"0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) # Update UI update_state(\"contour_min\",",
"array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else:",
"== Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.Surface: property.SetRepresentationToSurface()",
"= vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy default array contour_value",
"== Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface()",
"# ColorMap Callbacks # ----------------------------------------------------------------------------- def use_preset(actor, preset): lut =",
"update_state(\"contour_step\", contour_step) # Update View update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs):",
"# Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\") # Visibility Change",
"# ----------------------------------------------------------------------------- # trame Views # ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow)",
"\"parent\": \"1\", \"visible\": 1, \"name\": \"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"),",
"1, \"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\", \"visible\": 1, \"name\":",
"# ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx] contour_min,",
"v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider(",
"_id = event[\"id\"] _visibility = event[\"visible\"] if _id == \"1\":",
"dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays),",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\",",
"import vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore",
"update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() # -----------------------------------------------------------------------------",
"contour_card() with layout.content: # content components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\",",
"with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays),",
"def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view() # ----------------------------------------------------------------------------- # Pipeline",
"----------------------------------------------------------------------------- # ColorBy Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor, array): _min,",
"Change def visibility_change(event): _id = event[\"id\"] _visibility = event[\"visible\"] if",
"initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa # Required for",
"Rainbow = 0 Inverted_Rainbow = 1 Greyscale = 2 Inverted_Greyscale",
"contour_value) # Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value)",
"# ----------------------------------------------------------------------------- # VTK pipeline # ----------------------------------------------------------------------------- renderer = vtkRenderer()",
"# Extract Array/Field information dataset_arrays = [] fields = [",
"0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value) # Contour:",
"[ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in fields:",
"LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\": \"Inv",
"update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view global html_view if local_vs_remote: html_view",
"label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\",",
"noqa # Required for remote rendering factory initialization, not necessary",
"vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI Pipelines Widget #",
"== vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def",
"Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes: Boundaries, camera,",
"array) update_view() # ----------------------------------------------------------------------------- # ColorMap Callbacks # ----------------------------------------------------------------------------- def",
"vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx,",
"elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0)",
"update_representation(contour_actor, contour_representation) update_view() # ----------------------------------------------------------------------------- # ColorBy Callbacks # -----------------------------------------------------------------------------",
"_id == \"2\": # Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\")",
"= local_view else: html_view = remote_view # Update layout layout.content.children[0].children[0]",
"contour_step = 0.01 * (contour_max - contour_min) contour_value = 0.5",
"\"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3}, ], ), label=\"Representation\", hide_details=True,",
"Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\") # Visibility Change def",
"Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view()",
"----------------------------------------------------------------------------- def color_by_array(actor, array): _min, _max = array.get(\"range\") mapper =",
"3 class LookupTable: Rainbow = 0 Inverted_Rainbow = 1 Greyscale",
"0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs):",
"= { \"active_ui\": None, } # ----------------------------------------------------------------------------- # Main #",
"property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\")",
"= dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() # ----------------------------------------------------------------------------- # ColorMap Callbacks",
"property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff()",
"1}, {\"text\": \"Greyscale\", \"value\": 2}, {\"text\": \"Inv Greyscale\", \"value\": 3},",
"def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0),",
"Setup default representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour:",
"content = vuetify.VCardText(classes=\"py-2\") return content def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"):",
"Mesh: Setup default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() #",
"== Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode == Representation.Wireframe: property.SetRepresentationToWireframe()",
"_visibility = event[\"visible\"] if _id == \"1\": # Mesh mesh_actor.SetVisibility(_visibility)",
"renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update()",
"Cube Axes: Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\")",
"_id == \"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif _id == \"2\":",
"= dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array",
"1 Greyscale = 2 Inverted_Greyscale = 3 # ----------------------------------------------------------------------------- #",
"update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- # Contour Callbacks #",
"\"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field information dataset_arrays = [] fields",
"LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def",
"vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field in fields: field_arrays, association",
"), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0,",
"\"Points\", \"value\": 0}, {\"text\": \"Wireframe\", \"value\": 1}, {\"text\": \"Surface\", \"value\":",
"v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\",",
"import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- #",
"Contour: Apply rainbow color map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0)",
"property = actor.GetProperty() if mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff()",
"items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value),",
"# ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [ {\"id\": \"1\",",
"import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import (",
"\"range\": list(array_range), \"type\": association, } ) default_array = dataset_arrays[0] default_min,",
"== vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour",
"hide_details=True, dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- #",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"):",
"vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True,",
"property.EdgeVisibilityOff() elif mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode",
") # ----------------------------------------------------------------------------- # GUI Cards # ----------------------------------------------------------------------------- def ui_card(title,",
"= dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\") contour_step = 0.01 *",
"factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa # Required",
"update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- # Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\")",
"def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey",
"vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1 grey--text text--darken-3\",",
"vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\":",
"\"Greyscale\", \"value\": 2}, {\"text\": \"Inv Greyscale\", \"value\": 3}, ], ),",
"by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", )",
"1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh: Color by default array",
"components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer as drawer: #",
"Selection Change def actives_change(ids): _id = ids[0] if _id ==",
"None, } # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__",
"contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour: Color by default",
"dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1,",
"dense=True, ) content = vuetify.VCardText(classes=\"py-2\") return content def mesh_card(): with",
"default representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply",
"Array/Field information dataset_arrays = [] fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS),",
"contour_representation) update_view() # ----------------------------------------------------------------------------- # ColorBy Callbacks # ----------------------------------------------------------------------------- def",
"classes=\"mt-1\", hide_details=True, dense=True, ) # ----------------------------------------------------------------------------- # GUI # -----------------------------------------------------------------------------",
"Switch html_view global html_view if local_vs_remote: html_view = local_view else:",
"# Mesh: Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if",
"lut.SetValueRange(0.0, 1.0) elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0)",
"contour_min) contour_value = 0.5 * (contour_max + contour_min) contour.SetInputArrayToProcess(0, 0,",
"\"value\": 2}, {\"text\": \"Inv Greyscale\", \"value\": 3}, ], ), hide_details=True,",
"# ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- # Toolbar Callbacks",
"dense=True, ) def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\",",
"# ColorBy Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor, array): _min, _max",
"= vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view #",
"array.GetName(), \"value\": i, \"range\": list(array_range), \"type\": association, } ) default_array",
"default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True)",
"**kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx,",
"trame.layouts import SinglePageWithDrawer from trame.html import vtk, vuetify, widgets from",
"# Read Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() #",
"dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays),",
") vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True,",
"- contour_min) contour_value = 0.5 * (contour_max + contour_min) contour.SetInputArrayToProcess(0,",
"@change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view()",
"min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 * (default_max - default_min)),",
"update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): # Switch",
"styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # -----------------------------------------------------------------------------",
"property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn()",
"v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, ) with vuetify.VBtn(icon=True,",
"cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view global",
"vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa # Required for remote rendering",
"preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif",
"content def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=(",
"color map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0,",
"field for i in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range =",
"def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity)",
"from vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, )",
"surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow color map",
"# Contour: Setup default representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff()",
"mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper",
"classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\",",
"hide_details=True, dense=True, ) # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout",
"vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI Pipelines Widget # ----------------------------------------------------------------------------- def",
"renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader =",
"Read Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract",
"update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor,",
"vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\",",
"for # local rendering, but doesn't hurt to include it",
"default array contour_value = 0.5 * (default_max + default_min) contour.SetInputArrayToProcess(",
"v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, )",
"== \"2\": # Contour update_state(\"active_ui\", \"contour\") else: update_state(\"active_ui\", \"nothing\") #",
"local_view # ----------------------------------------------------------------------------- # Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update()",
"# ----------------------------------------------------------------------------- # ColorMap Callbacks # ----------------------------------------------------------------------------- def use_preset(actor, preset):",
"# Visibility Change def visibility_change(event): _id = event[\"id\"] _visibility =",
"actives_change(ids): _id = ids[0] if _id == \"1\": # Mesh",
"classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\",",
"renderer.AddActor(contour_actor) # Contour: ContourBy default array contour_value = 0.5 *",
"by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", )",
"= 0 Wireframe = 1 Surface = 2 SurfaceWithEdges =",
"reader.Update() # Extract Array/Field information dataset_arrays = [] fields =",
"# ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view",
"vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\":",
"def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [ {\"id\": \"1\", \"parent\": \"0\",",
"os from trame import change, update_state from trame.layouts import SinglePageWithDrawer",
"Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- # Toolbar",
"update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view() # -----------------------------------------------------------------------------",
"array): _min, _max = array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min,",
") # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\",",
"{\"text\": \"SurfaceWithEdges\", \"value\": 3}, ], ), label=\"Representation\", hide_details=True, dense=True, outlined=True,",
"**kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() # ----------------------------------------------------------------------------- #",
"# ----------------------------------------------------------------------------- # Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity,",
"pointer\", hide_details=True, dense=True, ) content = vuetify.VCardText(classes=\"py-2\") return content def",
"lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor,",
"# Required for remote rendering factory initialization, not necessary for",
"----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx] contour_min, contour_max",
"= 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content: # content",
"fields: field_arrays, association = field for i in range(field_arrays.GetNumberOfArrays()): array",
"update_view() # ----------------------------------------------------------------------------- # GUI Toolbar Buttons # ----------------------------------------------------------------------------- def",
"elif mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode ==",
"== '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1 grey--text text--darken-3\", style=\"user-select:",
"default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData()",
"mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view() #",
"vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 *",
"1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour: Color by default array",
"dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array =",
"mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow color map mesh_lut",
"# ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def",
"GUI Pipelines Widget # ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\",",
"vtkInteractorStyleSwitch # noqa # Required for remote rendering factory initialization,",
"== LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\")",
"vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes: Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds())",
"update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor,",
"vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field information dataset_arrays =",
"use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view()",
"(contour_max - contour_min) contour_value = 0.5 * (contour_max + contour_min)",
"update_view() # ----------------------------------------------------------------------------- # Pipeline Widget Callbacks # ----------------------------------------------------------------------------- #",
"rainbow color map contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0)",
"= 0.5 * (contour_max + contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"),",
"= contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() #",
"array = dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\") contour_step = 0.01",
"], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) # ----------------------------------------------------------------------------- #",
"trame.html import vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel import vtkDataObject from",
"# ----------------------------------------------------------------------------- # Representation Callbacks # ----------------------------------------------------------------------------- def update_representation(actor, mode):",
"vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup default representation to surface",
"vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view # ----------------------------------------------------------------------------- # Callbacks #",
"mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.Surface:",
") with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI Pipelines",
"\"value\": 1}, {\"text\": \"Surface\", \"value\": 2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3},",
"Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array =",
"), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0,",
"update_view() # ----------------------------------------------------------------------------- # ColorBy Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor,",
"remote rendering factory initialization, not necessary for # local rendering,",
"default_min) contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value)",
"global html_view if local_vs_remote: html_view = local_view else: html_view =",
"remote_view # Update layout layout.content.children[0].children[0] = html_view layout.flush_content() # Update",
"= vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow)",
"html_view = local_view # ----------------------------------------------------------------------------- # Callbacks # ----------------------------------------------------------------------------- def",
"Contour: Setup default representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() #",
"vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0},",
"Cube Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes: Boundaries,",
"Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation)",
"\"0\", \"visible\": 1, \"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\": \"1\", \"visible\":",
"trame Views # ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow,",
"{\"id\": \"1\", \"parent\": \"0\", \"visible\": 1, \"name\": \"Mesh\"}, {\"id\": \"2\",",
"1.0) elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0,",
"= os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants # ----------------------------------------------------------------------------- class Representation:",
"= vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor()",
"----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- # Toolbar Callbacks #",
"dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() # ----------------------------------------------------------------------------- # ColorMap Callbacks #",
"0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0,",
"else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array",
"update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view global html_view",
"Required for remote rendering factory initialization, not necessary for #",
"3 # ----------------------------------------------------------------------------- # VTK pipeline # ----------------------------------------------------------------------------- renderer =",
"max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) # ----------------------------------------------------------------------------- #",
"mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs):",
") with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [",
"from trame.layouts import SinglePageWithDrawer from trame.html import vtk, vuetify, widgets",
"\"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\": \"Inv Rainbow\", \"value\":",
"----------------------------------------------------------------------------- def use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable() if preset ==",
"Widget Callbacks # ----------------------------------------------------------------------------- # Selection Change def actives_change(ids): _id",
"contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube",
"dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # ----------------------------------------------------------------------------- # GUI",
"contour_lut = contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build()",
"Update layout layout.content.children[0].children[0] = html_view layout.flush_content() # Update View update_view()",
"update_state from trame.layouts import SinglePageWithDrawer from trame.html import vtk, vuetify,",
"preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif",
"default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value) # Contour: Setup default representation",
"off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\",",
"----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view =",
"contour_color_preset) update_view() # ----------------------------------------------------------------------------- # Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\")",
"ui card layout.state = { \"active_ui\": None, } # -----------------------------------------------------------------------------",
"# ----------------------------------------------------------------------------- # Constants # ----------------------------------------------------------------------------- class Representation: Points =",
"\"1\", \"parent\": \"0\", \"visible\": 1, \"name\": \"Mesh\"}, {\"id\": \"2\", \"parent\":",
"Apply rainbow color map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0,",
"step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) # ----------------------------------------------------------------------------- # GUI",
"contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow color map contour_lut",
"# VTK pipeline # ----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow =",
"cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes: Boundaries, camera, and",
"cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame Views #",
"def update_representation(actor, mode): property = actor.GetProperty() if mode == Representation.Points:",
"mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode == Representation.Wireframe:",
"with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\":",
"----------------------------------------------------------------------------- # GUI Cards # ----------------------------------------------------------------------------- def ui_card(title, ui_name): with",
"== vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes",
"Representation: Points = 0 Wireframe = 1 Surface = 2",
"mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh: Color",
"0.5 * (contour_max + contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\"))",
"cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame",
"= ids[0] if _id == \"1\": # Mesh update_state(\"active_ui\", \"mesh\")",
"0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) # Update UI update_state(\"contour_min\", contour_min)",
"vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view], ) # State use to",
"def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view() # ----------------------------------------------------------------------------- # Opacity",
"cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame Views # ----------------------------------------------------------------------------- local_view",
"mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh:",
"vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy",
"Axes: Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\")",
"----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True,",
"vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, ) with",
"# ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view)",
"= array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\")",
"0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"):",
"step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) def contour_card(): with ui_card(title=\"Contour\",",
") vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01",
"Wireframe = 1 Surface = 2 SurfaceWithEdges = 3 class",
"to track active ui card layout.state = { \"active_ui\": None,",
"hurt to include it import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY =",
"= vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view # ----------------------------------------------------------------------------- # Callbacks",
"from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper,",
"update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view()",
"+ contour_min) contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) #",
"----------------------------------------------------------------------------- # Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs):",
"= 1 Surface = 2 SurfaceWithEdges = 3 class LookupTable:",
"actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else:",
"@change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view() # ----------------------------------------------------------------------------- #",
"----------------------------------------------------------------------------- # Selection Change def actives_change(ids): _id = ids[0] if",
"fill-height\", children=[html_view], ) # State use to track active ui",
"array.GetRange() dataset_arrays.append( { \"text\": array.GetName(), \"value\": i, \"range\": list(array_range), \"type\":",
"else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort())",
"], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0),",
"contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData()",
"contour.SetInputArrayToProcess(0, 0, 0, array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) # Update UI",
"dataset_arrays[0] default_min, default_max = default_array.get(\"range\") # Mesh mesh_mapper = vtkDataSetMapper()",
"Setup default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh:",
"outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color",
"# ----------------------------------------------------------------------------- # Pipeline Widget Callbacks # ----------------------------------------------------------------------------- # Selection",
"= actor.GetProperty() if mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif",
"actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) # ----------------------------------------------------------------------------- # GUI Cards",
"mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup default",
"\"value\": 0}, {\"text\": \"Wireframe\", \"value\": 1}, {\"text\": \"Surface\", \"value\": 2},",
"_max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True)",
"\"value\": 1}, {\"text\": \"Greyscale\", \"value\": 2}, {\"text\": \"Inv Greyscale\", \"value\":",
"* (default_max - default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect(",
"widgets.GitTree( sources=( \"pipeline\", [ {\"id\": \"1\", \"parent\": \"0\", \"visible\": 1,",
"class LookupTable: Rainbow = 0 Inverted_Rainbow = 1 Greyscale =",
"contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes = vtkCubeAxesActor() renderer.AddActor(cube_axes) #",
"mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper()",
"Mesh: Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\")",
"mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\") def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array)",
"default_max), step=(\"contour_step\", 0.01 * (default_max - default_min)), label=\"Value\", classes=\"my-1\", hide_details=True,",
"Buttons # ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\",",
"information dataset_arrays = [] fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(),",
"# Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity)",
"[ {\"id\": \"1\", \"parent\": \"0\", \"visible\": 1, \"name\": \"Mesh\"}, {\"id\":",
"= vtkCubeAxesActor() renderer.AddActor(cube_axes) # Cube Axes: Boundaries, camera, and styling",
"representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow",
"layout.toolbar: # toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer",
"= vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup default representation to",
"contour_value = 0.5 * (default_max + default_min) contour.SetInputArrayToProcess( 0, 0,",
"vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy default array contour_value =",
"actor.GetProperty() if mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode",
") content = vuetify.VCardText(classes=\"py-2\") return content def mesh_card(): with ui_card(title=\"Mesh\",",
"1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) def",
"vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML import",
"lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666)",
"elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation,",
"Inverted_Rainbow = 1 Greyscale = 2 Inverted_Greyscale = 3 #",
"dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\",",
"Constants # ----------------------------------------------------------------------------- class Representation: Points = 0 Wireframe =",
"import vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader",
"widgets from vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter from",
"html_view.update() # ----------------------------------------------------------------------------- # Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def",
"= actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0)",
"0}, {\"text\": \"Inv Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\", \"value\": 2},",
"1.0) elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0,",
"= vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh:",
"= remote_view # Update layout layout.content.children[0].children[0] = html_view layout.flush_content() #",
"= vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader = vtkXMLUnstructuredGridReader()",
"# ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__ == \"__main__\":",
"# GUI Toolbar Buttons # ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\",",
"# ----------------------------------------------------------------------------- # GUI Pipelines Widget # ----------------------------------------------------------------------------- def pipeline_widget():",
"0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\")",
"\"SurfaceWithEdges\", \"value\": 3}, ], ), label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\",",
"+ default_min) contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0,",
"----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor =",
"0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0,",
"= actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData()",
"v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with",
"\"1\": # Mesh update_state(\"active_ui\", \"mesh\") elif _id == \"2\": #",
"ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1",
"def update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- # Toolbar Callbacks # -----------------------------------------------------------------------------",
"\"mesh\") elif _id == \"2\": # Contour update_state(\"active_ui\", \"contour\") else:",
"2}, {\"text\": \"Inv Greyscale\", \"value\": 3}, ], ), hide_details=True, dense=True,",
"Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\")",
"if _id == \"1\": # Mesh update_state(\"active_ui\", \"mesh\") elif _id",
"if preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0)",
"layout.content: # content components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view], )",
"# ----------------------------------------------------------------------------- # GUI Cards # ----------------------------------------------------------------------------- def ui_card(title, ui_name):",
"vtk.VtkLocalView(renderWindow) remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view # -----------------------------------------------------------------------------",
"\"contour\") else: update_state(\"active_ui\", \"nothing\") # Visibility Change def visibility_change(event): _id",
"GUI Cards # ----------------------------------------------------------------------------- def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui ==",
"vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera()",
"@change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs):",
"= array.get(\"range\") contour_step = 0.01 * (contour_max - contour_min) contour_value",
"# ----------------------------------------------------------------------------- # GUI Toolbar Buttons # ----------------------------------------------------------------------------- def standard_buttons():",
"**kwargs): use_preset(contour_actor, contour_color_preset) update_view() # ----------------------------------------------------------------------------- # Opacity Callbacks #",
"mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow color map mesh_lut = mesh_mapper.GetLookupTable()",
"min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) # -----------------------------------------------------------------------------",
"] for field in fields: field_arrays, association = field for",
"update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array)",
"import vtkInteractorStyleSwitch # noqa # Required for remote rendering factory",
"dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True,",
"vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1 grey--text text--darken-3\", style=\"user-select: none; cursor:",
"with layout.toolbar: # toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with",
"field in fields: field_arrays, association = field for i in",
"classes=\"pa-0 fill-height\", children=[html_view], ) # State use to track active",
"contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour: ContourBy default array",
"dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow),",
"(default_max + default_min) contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\") )",
"if mode == Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode ==",
"html_view global html_view if local_vs_remote: html_view = local_view else: html_view",
"update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) # Update",
"# Mesh: Setup default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff()",
"Pipeline Widget Callbacks # ----------------------------------------------------------------------------- # Selection Change def actives_change(ids):",
"_id == \"1\": # Mesh update_state(\"active_ui\", \"mesh\") elif _id ==",
"dataset_arrays = [] fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS),",
"vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0},",
"= 3 # ----------------------------------------------------------------------------- # VTK pipeline # ----------------------------------------------------------------------------- renderer",
"@change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- # Contour",
"ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True,",
"vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) # Required for interacter",
"lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0)",
"# Required for interacter factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch",
"vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer as drawer: # drawer",
"field_arrays, association = field for i in range(field_arrays.GetNumberOfArrays()): array =",
"2}, {\"text\": \"SurfaceWithEdges\", \"value\": 3}, ], ), label=\"Representation\", hide_details=True, dense=True,",
"vtkRenderWindow, vtkRenderWindowInteractor, ) # Required for interacter factory initialization from",
"# Selection Change def actives_change(ids): _id = ids[0] if _id",
"\"name\": \"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) #",
"0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset)",
"max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 * (default_max - default_min)), label=\"Value\", classes=\"my-1\",",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1,",
"mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup default representation",
"ids[0] if _id == \"1\": # Mesh update_state(\"active_ui\", \"mesh\") elif",
"Required for interacter factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch #",
"classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\",",
"Update View update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view()",
"by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS:",
"array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData() mapper.SetScalarVisibility(True) mapper.SetUseLookupTableScalarRange(True) @change(\"mesh_color_array_idx\")",
"remote_view = vtk.VtkRemoteView(renderWindow, interactive_ratio=(1,)) html_view = local_view # ----------------------------------------------------------------------------- #",
"@change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation,",
"event[\"visible\"] if _id == \"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif _id",
"# GUI # ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with",
"contour_lut.Build() # Contour: Color by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\"))",
"def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs):",
"Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx]",
"and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() #",
"visibility_change(event): _id = event[\"id\"] _visibility = event[\"visible\"] if _id ==",
"update_view() # ----------------------------------------------------------------------------- # Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def",
"if _id == \"1\": # Mesh mesh_actor.SetVisibility(_visibility) elif _id ==",
"ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1",
"mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\", [",
"rainbow color map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0)",
"contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour: Color by default array contour_mapper.GetLookupTable().SetRange(default_min,",
"local_vs_remote: html_view = local_view else: html_view = remote_view # Update",
"= event[\"id\"] _visibility = event[\"visible\"] if _id == \"1\": #",
"factory initialization, not necessary for # local rendering, but doesn't",
"elif preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0)",
"classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True,",
"items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect(",
"def update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor, array) update_view() #",
"@change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx] contour_min, contour_max =",
"# ----------------------------------------------------------------------------- def use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable() if preset",
"label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"):",
"py-1 grey--text text--darken-3\", style=\"user-select: none; cursor: pointer\", hide_details=True, dense=True, )",
"default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData()",
"vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper)",
"map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0)",
"Contour: Color by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\")",
"lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Inverted_Rainbow:",
"update_state(\"active_ui\", \"nothing\") # Visibility Change def visibility_change(event): _id = event[\"id\"]",
"\"value\": 0}, {\"text\": \"Inv Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\", \"value\":",
"label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\",",
"track active ui card layout.state = { \"active_ui\": None, }",
"trame import change, update_state from trame.layouts import SinglePageWithDrawer from trame.html",
"# Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\",",
"# ----------------------------------------------------------------------------- # Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx,",
"# ----------------------------------------------------------------------------- def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\",",
"contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 * (default_max -",
"renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() #",
"mesh_card() contour_card() with layout.content: # content components vuetify.VContainer( fluid=True, classes=\"pa-0",
"\"value\": 3}, ], ), label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\", )",
"label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) # ----------------------------------------------------------------------------- # GUI #",
"Mesh: Apply rainbow color map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0)",
"elif mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode ==",
"# Mesh mesh_actor.SetVisibility(_visibility) elif _id == \"2\": # Contour contour_actor.SetVisibility(_visibility)",
"v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max), step=(\"contour_step\", 0.01 * (default_max",
"= 0 Inverted_Rainbow = 1 Greyscale = 2 Inverted_Greyscale =",
"# Update View update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value))",
"== \"1\": # Mesh update_state(\"active_ui\", \"mesh\") elif _id == \"2\":",
"classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\", [",
"outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=(",
"step=(\"contour_step\", 0.01 * (default_max - default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True,",
"property.EdgeVisibilityOff() elif mode == Representation.SurfaceWithEdges: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def",
"Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor",
") vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True,",
"with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1 grey--text",
"Callbacks # ----------------------------------------------------------------------------- # Selection Change def actives_change(ids): _id =",
"update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view() # ----------------------------------------------------------------------------- # Opacity Callbacks",
"\"visible\": 1, \"name\": \"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"),",
"\"active_ui\": None, } # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if",
"----------------------------------------------------------------------------- # Pipeline Widget Callbacks # ----------------------------------------------------------------------------- # Selection Change",
"update_state(\"active_ui\", \"mesh\") elif _id == \"2\": # Contour update_state(\"active_ui\", \"contour\")",
"rendering factory initialization, not necessary for # local rendering, but",
"contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube Axes cube_axes =",
"----------------------------------------------------------------------------- class Representation: Points = 0 Wireframe = 1 Surface",
"cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame Views # -----------------------------------------------------------------------------",
"contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True)",
"Callbacks # ----------------------------------------------------------------------------- def use_preset(actor, preset): lut = actor.GetMapper().GetLookupTable() if",
"outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\",",
"Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges()",
"import SinglePageWithDrawer from trame.html import vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel",
"\"text\": array.GetName(), \"value\": i, \"range\": list(array_range), \"type\": association, } )",
"\"nothing\") # Visibility Change def visibility_change(event): _id = event[\"id\"] _visibility",
"i in range(field_arrays.GetNumberOfArrays()): array = field_arrays.GetArray(i) array_range = array.GetRange() dataset_arrays.append(",
"update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view() # -----------------------------------------------------------------------------",
"items=( \"representations\", [ {\"text\": \"Points\", \"value\": 0}, {\"text\": \"Wireframe\", \"value\":",
"label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\",",
"{\"text\": \"Inv Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\", \"value\": 2}, {\"text\":",
"} # ----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__ ==",
"v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with",
"{\"text\": \"Inv Greyscale\", \"value\": 3}, ], ), hide_details=True, dense=True, outlined=True,",
"# noqa CURRENT_DIRECTORY = os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants #",
"contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow color map contour_lut =",
"grey--text text--darken-3\", style=\"user-select: none; cursor: pointer\", hide_details=True, dense=True, ) content",
"in fields: field_arrays, association = field for i in range(field_arrays.GetNumberOfArrays()):",
"----------------------------------------------------------------------------- # GUI Pipelines Widget # ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree(",
"default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour",
"contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor =",
"label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True): with",
"with layout.drawer as drawer: # drawer components drawer.width = 325",
"vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) # Required for interacter factory initialization",
"----------------------------------------------------------------------------- # ColorMap Callbacks # ----------------------------------------------------------------------------- def use_preset(actor, preset): lut",
"v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\":",
"# GUI Pipelines Widget # ----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=(",
"lut.SetValueRange(1.0, 1.0) elif preset == LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0)",
"# ----------------------------------------------------------------------------- # ColorBy Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor, array):",
"[ {\"text\": \"Points\", \"value\": 0}, {\"text\": \"Wireframe\", \"value\": 1}, {\"text\":",
"= dataset_arrays[0] default_min, default_max = default_array.get(\"range\") # Mesh mesh_mapper =",
"1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) #",
"**kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view",
"mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666, 0.0) mesh_lut.SetSaturationRange(1.0, 1.0) mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build()",
"default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) # Cube",
"with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0),",
"def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- # Contour Callbacks",
"@change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset,",
"ContourBy default array contour_value = 0.5 * (default_max + default_min)",
"\"Inv Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\", \"value\": 2}, {\"text\": \"Inv",
"@change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view global html_view if",
"# drawer components drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card()",
"\"2\", \"parent\": \"1\", \"visible\": 1, \"name\": \"Contour\"}, ], ), actives_change=(actives_change,",
"else: html_view = remote_view # Update layout layout.content.children[0].children[0] = html_view",
"= local_view # ----------------------------------------------------------------------------- # Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs):",
"Cards # ----------------------------------------------------------------------------- def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"):",
"label=\"Colormap\", v_model=(\"mesh_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0},",
"0.0) lut.SetValueRange(0.0, 1.0) elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0,",
"**kwargs): contour.SetValue(0, float(contour_value)) update_view() # ----------------------------------------------------------------------------- # Pipeline Widget Callbacks",
"== LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif preset",
"Inverted_Greyscale = 3 # ----------------------------------------------------------------------------- # VTK pipeline # -----------------------------------------------------------------------------",
"standard_buttons() with layout.drawer as drawer: # drawer components drawer.width =",
"surface mesh_actor.GetProperty().SetRepresentationToSurface() mesh_actor.GetProperty().SetPointSize(1) mesh_actor.GetProperty().EdgeVisibilityOff() # Mesh: Apply rainbow color map",
"by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", )",
"use_preset(contour_actor, contour_color_preset) update_view() # ----------------------------------------------------------------------------- # Opacity Callbacks # -----------------------------------------------------------------------------",
"mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour = vtkContourFilter() contour.SetInputConnection(reader.GetOutputPort()) contour_mapper =",
"# toolbar components vuetify.VSpacer() vuetify.VDivider(vertical=True, classes=\"mx-2\") standard_buttons() with layout.drawer as",
"[] fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for",
"default_min, default_max = default_array.get(\"range\") # Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort())",
"contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) # Update View update_view() @change(\"contour_value\")",
"drawer components drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with",
"Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor, array): _min, _max = array.get(\"range\")",
"# ----------------------------------------------------------------------------- # Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility,",
"sources=( \"pipeline\", [ {\"id\": \"1\", \"parent\": \"0\", \"visible\": 1, \"name\":",
"label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=( \"representations\",",
"html_view layout.flush_content() # Update View update_view() # ----------------------------------------------------------------------------- # Representation",
"def mesh_card(): with ui_card(title=\"Mesh\", ui_name=\"mesh\"): vuetify.VSelect( v_model=(\"mesh_representation\", Representation.Surface), items=( \"representations\",",
"dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"contour_color_preset\", LookupTable.Rainbow),",
"UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) #",
"def color_by_array(actor, array): _min, _max = array.get(\"range\") mapper = actor.GetMapper()",
"----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar",
"= vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) # Contour:",
"not necessary for # local rendering, but doesn't hurt to",
"contour_min, contour_max = array.get(\"range\") contour_step = 0.01 * (contour_max -",
"Visibility Change def visibility_change(event): _id = event[\"id\"] _visibility = event[\"visible\"]",
"# Pipeline Widget Callbacks # ----------------------------------------------------------------------------- # Selection Change def",
"----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility) update_view() @change(\"local_vs_remote\") def update_local_vs_remote(local_vs_remote,",
"v_model=(\"contour_color_preset\", LookupTable.Rainbow), items=( \"colormaps\", [ {\"text\": \"Rainbow\", \"value\": 0}, {\"text\":",
"else: update_state(\"active_ui\", \"nothing\") # Visibility Change def visibility_change(event): _id =",
"**kwargs): update_representation(mesh_actor, mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation)",
"----------------------------------------------------------------------------- # trame Views # ----------------------------------------------------------------------------- local_view = vtk.VtkLocalView(renderWindow) remote_view",
"_min, _max = array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max)",
"drawer.width = 325 pipeline_widget() vuetify.VDivider(classes=\"mb-2\") mesh_card() contour_card() with layout.content: #",
"actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0,",
"= array.GetRange() dataset_arrays.append( { \"text\": array.GetName(), \"value\": i, \"range\": list(array_range),",
"mesh_lut.SetValueRange(1.0, 1.0) mesh_lut.Build() # Mesh: Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\"))",
"update_view() # ----------------------------------------------------------------------------- # Representation Callbacks # ----------------------------------------------------------------------------- def update_representation(actor,",
"# ----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor",
"style=\"user-select: none; cursor: pointer\", hide_details=True, dense=True, ) content = vuetify.VCardText(classes=\"py-2\")",
") # Required for interacter factory initialization from vtkmodules.vtkInteractionStyle import",
"array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs):",
"= vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\")) reader.Update() # Extract Array/Field information dataset_arrays",
"== LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset",
"= 2 SurfaceWithEdges = 3 class LookupTable: Rainbow = 0",
"update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\") contour_step",
"Mesh mesh_actor.SetVisibility(_visibility) elif _id == \"2\": # Contour contour_actor.SetVisibility(_visibility) update_view()",
"vtkRenderWindowInteractor() renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY,",
"), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), ) # ----------------------------------------------------------------------------- # GUI",
"array.get(\"type\"), array.get(\"text\")) contour.SetValue(0, contour_value) # Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\",",
"contour_value) update_state(\"contour_step\", contour_step) # Update View update_view() @change(\"contour_value\") def update_contour_value(contour_value,",
"), label=\"Representation\", hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VRow(classes=\"pt-2\", dense=True):",
"# Callbacks # ----------------------------------------------------------------------------- def update_view(**kwargs): html_view.update() # ----------------------------------------------------------------------------- #",
"mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData()",
"color_by_array(contour_actor, array) update_view() # ----------------------------------------------------------------------------- # ColorMap Callbacks # -----------------------------------------------------------------------------",
"* (default_max + default_min) contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\")",
"mesh_lut.Build() # Mesh: Color by default array mesh_mapper.SelectColorArray(default_array.get(\"text\")) mesh_mapper.GetLookupTable().SetRange(default_min, default_max)",
"# Cube Axes: Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\")",
"# local rendering, but doesn't hurt to include it import",
"], ), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0),",
"default_array = dataset_arrays[0] default_min, default_max = default_array.get(\"range\") # Mesh mesh_mapper",
"doesn't hurt to include it import vtkmodules.vtkRenderingOpenGL2 # noqa CURRENT_DIRECTORY",
"contour_value = 0.5 * (contour_max + contour_min) contour.SetInputArrayToProcess(0, 0, 0,",
"contour_mapper = vtkDataSetMapper() contour_mapper.SetInputConnection(contour.GetOutputPort()) contour_actor = vtkActor() contour_actor.SetMapper(contour_mapper) renderer.AddActor(contour_actor) #",
"array_range = array.GetRange() dataset_arrays.append( { \"text\": array.GetName(), \"value\": i, \"range\":",
"html_view = local_view else: html_view = remote_view # Update layout",
"dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, )",
"array.get(\"range\") contour_step = 0.01 * (contour_max - contour_min) contour_value =",
"# ----------------------------------------------------------------------------- # Selection Change def actives_change(ids): _id = ids[0]",
"0}, {\"text\": \"Wireframe\", \"value\": 1}, {\"text\": \"Surface\", \"value\": 2}, {\"text\":",
"vuetify.VSlider( v_model=(\"mesh_opacity\", 1.0), min=0, max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True,",
"= SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: # toolbar components vuetify.VSpacer()",
"update_view() # ----------------------------------------------------------------------------- # ColorMap Callbacks # ----------------------------------------------------------------------------- def use_preset(actor,",
"Mesh update_state(\"active_ui\", \"mesh\") elif _id == \"2\": # Contour update_state(\"active_ui\",",
"vtkRenderWindowInteractor, ) # Required for interacter factory initialization from vtkmodules.vtkInteractionStyle",
"property.EdgeVisibilityOff() elif mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode",
"1 Surface = 2 SurfaceWithEdges = 3 class LookupTable: Rainbow",
"def update_mesh_color_by_name(mesh_color_array_idx, **kwargs): array = dataset_arrays[mesh_color_array_idx] color_by_array(mesh_actor, array) update_view() @change(\"contour_color_array_idx\")",
"layout.drawer as drawer: # drawer components drawer.width = 325 pipeline_widget()",
"use to track active ui card layout.state = { \"active_ui\":",
"\"representations\", [ {\"text\": \"Points\", \"value\": 0}, {\"text\": \"Wireframe\", \"value\": 1},",
"mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mesh_mapper.SetScalarVisibility(True) mesh_mapper.SetUseLookupTableScalarRange(True) # Contour contour = vtkContourFilter()",
"card layout.state = { \"active_ui\": None, } # ----------------------------------------------------------------------------- #",
"vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True,",
"True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"):",
"hide_details=True, dense=True, ) def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour",
"# Contour Callbacks # ----------------------------------------------------------------------------- @change(\"contour_by_array_idx\") def update_contour_by(contour_by_array_idx, **kwargs): array",
"local rendering, but doesn't hurt to include it import vtkmodules.vtkRenderingOpenGL2",
"contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\", 0), items=(\"array_list\",",
"outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\", contour_value), min=(\"contour_min\", default_min), max=(\"contour_max\", default_max),",
"# Toolbar Callbacks # ----------------------------------------------------------------------------- @change(\"cube_axes_visibility\") def update_cube_axes_visibility(cube_axes_visibility, **kwargs): cube_axes.SetVisibility(cube_axes_visibility)",
"camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera()) cube_axes.SetXLabelFormat(\"%6.1f\") cube_axes.SetYLabelFormat(\"%6.1f\") cube_axes.SetZLabelFormat(\"%6.1f\") cube_axes.SetFlyModeToOuterEdges() renderer.ResetCamera()",
"array) update_view() @change(\"contour_color_array_idx\") def update_contour_color_by_name(contour_color_array_idx, **kwargs): array = dataset_arrays[contour_color_array_idx] color_by_array(contour_actor,",
"mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) #",
"ColorBy Callbacks # ----------------------------------------------------------------------------- def color_by_array(actor, array): _min, _max =",
"0), items=(\"array_list\", dataset_arrays), hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_value\",",
"update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- #",
"classes=\"mx-2\") standard_buttons() with layout.drawer as drawer: # drawer components drawer.width",
"interacter factory initialization from vtkmodules.vtkInteractionStyle import vtkInteractorStyleSwitch # noqa #",
"import ( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow, vtkRenderWindowInteractor, ) # Required",
"property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOff() elif",
"Opacity Callbacks # ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view()",
") vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox(",
"from vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore import vtkContourFilter from vtkmodules.vtkIOXML",
"initialization, not necessary for # local rendering, but doesn't hurt",
"= 3 class LookupTable: Rainbow = 0 Inverted_Rainbow = 1",
"array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else:",
"pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [ {\"id\": \"1\", \"parent\": \"0\", \"visible\":",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Colormap\", v_model=(\"mesh_color_preset\",",
"to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow color",
"max=1, step=0.1, label=\"Opacity\", classes=\"mt-1\", hide_details=True, dense=True, ) def contour_card(): with",
"{ \"active_ui\": None, } # ----------------------------------------------------------------------------- # Main # -----------------------------------------------------------------------------",
"os.path.abspath(os.path.dirname(__file__)) # ----------------------------------------------------------------------------- # Constants # ----------------------------------------------------------------------------- class Representation: Points",
"preset): lut = actor.GetMapper().GetLookupTable() if preset == LookupTable.Rainbow: lut.SetHueRange(0.666, 0.0)",
"float(contour_value)) update_view() # ----------------------------------------------------------------------------- # Pipeline Widget Callbacks # -----------------------------------------------------------------------------",
"lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif preset == LookupTable.Inverted_Greyscale:",
"VTK pipeline # ----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow = vtkRenderWindow()",
"representation to surface contour_actor.GetProperty().SetRepresentationToSurface() contour_actor.GetProperty().SetPointSize(1) contour_actor.GetProperty().EdgeVisibilityOff() # Contour: Apply rainbow",
"dataset_arrays.append( { \"text\": array.GetName(), \"value\": i, \"range\": list(array_range), \"type\": association,",
"# Mesh: Apply rainbow color map mesh_lut = mesh_mapper.GetLookupTable() mesh_lut.SetHueRange(0.666,",
"with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0), items=(\"array_list\", dataset_arrays), hide_details=True,",
"{\"text\": \"Rainbow\", \"value\": 0}, {\"text\": \"Inv Rainbow\", \"value\": 1}, {\"text\":",
"classes=\"mx-1\", hide_details=True, dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") # -----------------------------------------------------------------------------",
"\"Rainbow\", \"value\": 0}, {\"text\": \"Inv Rainbow\", \"value\": 1}, {\"text\": \"Greyscale\",",
"layout layout.content.children[0].children[0] = html_view layout.flush_content() # Update View update_view() #",
"mesh_representation) update_view() @change(\"contour_representation\") def update_contour_representation(contour_representation, **kwargs): update_representation(contour_actor, contour_representation) update_view() #",
"* (contour_max - contour_min) contour_value = 0.5 * (contour_max +",
"# Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper)",
"from vtkmodules.vtkIOXML import vtkXMLUnstructuredGridReader from vtkmodules.vtkRenderingAnnotation import vtkCubeAxesActor from vtkmodules.vtkRenderingCore",
"= [] fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ]",
"# Update View update_view() # ----------------------------------------------------------------------------- # Representation Callbacks #",
"contour_max = array.get(\"range\") contour_step = 0.01 * (contour_max - contour_min)",
"property.SetRepresentationToSurface() property.SetPointSize(1) property.EdgeVisibilityOn() @change(\"mesh_representation\") def update_mesh_representation(mesh_representation, **kwargs): update_representation(mesh_actor, mesh_representation) update_view()",
"contour.SetValue(0, contour_value) # Update UI update_state(\"contour_min\", contour_min) update_state(\"contour_max\", contour_max) update_state(\"contour_value\",",
"preset == LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif",
"**kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # ----------------------------------------------------------------------------- # Contour Callbacks # -----------------------------------------------------------------------------",
"**kwargs): array = dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\") contour_step =",
"classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\",",
"# ----------------------------------------------------------------------------- @change(\"mesh_opacity\") def update_mesh_opacity(mesh_opacity, **kwargs): mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def",
"off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\") #",
"# ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar: #",
"1, \"name\": \"Contour\"}, ], ), actives_change=(actives_change, \"[$event]\"), visibility_change=(visibility_change, \"[$event]\"), )",
"# State use to track active ui card layout.state =",
"def update_local_vs_remote(local_vs_remote, **kwargs): # Switch html_view global html_view if local_vs_remote:",
"hide_details=True, dense=True, ) content = vuetify.VCardText(classes=\"py-2\") return content def mesh_card():",
"mesh_actor.GetProperty().SetOpacity(mesh_opacity) update_view() @change(\"contour_opacity\") def update_contour_opacity(contour_opacity, **kwargs): contour_actor.GetProperty().SetOpacity(contour_opacity) update_view() # -----------------------------------------------------------------------------",
"View update_view() # ----------------------------------------------------------------------------- # Representation Callbacks # ----------------------------------------------------------------------------- def",
"mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor) # Mesh: Setup default representation to surface mesh_actor.GetProperty().SetRepresentationToSurface()",
"with layout.content: # content components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view],",
"renderer.ResetCamera() # ----------------------------------------------------------------------------- # trame Views # ----------------------------------------------------------------------------- local_view =",
"default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface), items=(",
"update_state(\"contour_max\", contour_max) update_state(\"contour_value\", contour_value) update_state(\"contour_step\", contour_step) # Update View update_view()",
"children=[html_view], ) # State use to track active ui card",
"vtk, vuetify, widgets from vtkmodules.vtkCommonDataModel import vtkDataObject from vtkmodules.vtkFiltersCore import",
"on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\",",
"def update_contour_by(contour_by_array_idx, **kwargs): array = dataset_arrays[contour_by_array_idx] contour_min, contour_max = array.get(\"range\")",
"classes=\"mt-1\", hide_details=True, dense=True, ) def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect(",
"0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour: Color by",
"_id == \"2\": # Contour contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- #",
"if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: contour_mapper.SetScalarModeToUsePointFieldData() else: contour_mapper.SetScalarModeToUseCellFieldData() contour_mapper.SetScalarVisibility(True) contour_mapper.SetUseLookupTableScalarRange(True) #",
"# Contour contour_actor.SetVisibility(_visibility) update_view() # ----------------------------------------------------------------------------- # GUI Toolbar Buttons",
"hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=\"$vuetify.theme.dark\", on_icon=\"mdi-lightbulb-off-outline\", off_icon=\"mdi-lightbulb-outline\", classes=\"mx-1\", hide_details=True, dense=True,",
"contour_mapper.GetLookupTable() contour_lut.SetHueRange(0.666, 0.0) contour_lut.SetSaturationRange(1.0, 1.0) contour_lut.SetValueRange(1.0, 1.0) contour_lut.Build() # Contour:",
"def update_mesh_color_preset(mesh_color_preset, **kwargs): use_preset(mesh_actor, mesh_color_preset) update_view() @change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs):",
"----------------------------------------------------------------------------- def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle( title,",
"with vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"contour_color_array_idx\", 0),",
"i, \"range\": list(array_range), \"type\": association, } ) default_array = dataset_arrays[0]",
"- default_min)), label=\"Value\", classes=\"my-1\", hide_details=True, dense=True, ) vuetify.VSelect( v_model=(\"contour_representation\", Representation.Surface),",
"lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0) lut.Build() @change(\"mesh_color_preset\") def update_mesh_color_preset(mesh_color_preset,",
"_max = array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if",
"# ----------------------------------------------------------------------------- def ui_card(title, ui_name): with vuetify.VCard(v_show=f\"active_ui == '{ui_name}'\"): vuetify.VCardTitle(",
"hide_details=True, dense=True, ) vuetify.VCheckbox( v_model=(\"local_vs_remote\", True), on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True,",
"Mesh mesh_mapper = vtkDataSetMapper() mesh_mapper.SetInputConnection(reader.GetOutputPort()) mesh_actor = vtkActor() mesh_actor.SetMapper(mesh_mapper) renderer.AddActor(mesh_actor)",
"'{ui_name}'\"): vuetify.VCardTitle( title, classes=\"grey lighten-1 py-1 grey--text text--darken-3\", style=\"user-select: none;",
"vuetify.VRow(classes=\"pt-2\", dense=True): with vuetify.VCol(cols=\"6\"): vuetify.VSelect( label=\"Color by\", v_model=(\"mesh_color_array_idx\", 0), items=(\"array_list\",",
"fields = [ (reader.GetOutput().GetPointData(), vtkDataObject.FIELD_ASSOCIATION_POINTS), (reader.GetOutput().GetCellData(), vtkDataObject.FIELD_ASSOCIATION_CELLS), ] for field",
"@change(\"contour_color_preset\") def update_contour_color_preset(contour_color_preset, **kwargs): use_preset(contour_actor, contour_color_preset) update_view() # ----------------------------------------------------------------------------- #",
"text--darken-3\", style=\"user-select: none; cursor: pointer\", hide_details=True, dense=True, ) content =",
"renderWindowInteractor.SetRenderWindow(renderWindow) renderWindowInteractor.GetInteractorStyle().SetCurrentStyleToTrackballCamera() # Read Data reader = vtkXMLUnstructuredGridReader() reader.SetFileName(os.path.join(CURRENT_DIRECTORY, \"../data/disk_out_ref.vtu\"))",
"----------------------------------------------------------------------------- def pipeline_widget(): widgets.GitTree( sources=( \"pipeline\", [ {\"id\": \"1\", \"parent\":",
"hide_details=True, dense=True, outlined=True, classes=\"pt-1\", ) vuetify.VSlider( v_model=(\"contour_opacity\", 1.0), min=0, max=1,",
"def standard_buttons(): vuetify.VCheckbox( v_model=(\"cube_axes_visibility\", True), on_icon=\"mdi-cube-outline\", off_icon=\"mdi-cube-off-outline\", classes=\"mx-1\", hide_details=True, dense=True,",
"----------------------------------------------------------------------------- # Main # ----------------------------------------------------------------------------- if __name__ == \"__main__\": layout.start()",
"import vtkCubeAxesActor from vtkmodules.vtkRenderingCore import ( vtkActor, vtkDataSetMapper, vtkRenderer, vtkRenderWindow,",
"content components vuetify.VContainer( fluid=True, classes=\"pa-0 fill-height\", children=[html_view], ) # State",
"Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1) property.EdgeVisibilityOff() elif mode == Representation.Surface: property.SetRepresentationToSurface() property.SetPointSize(1)",
"on_icon=\"mdi-lan-disconnect\", off_icon=\"mdi-lan-connect\", classes=\"mx-1\", hide_details=True, dense=True, ) with vuetify.VBtn(icon=True, click=\"$refs.view.resetCamera()\"): vuetify.VIcon(\"mdi-crop-free\")",
"contour.SetValue(0, contour_value) # Contour: Setup default representation to surface contour_actor.GetProperty().SetRepresentationToSurface()",
") def contour_card(): with ui_card(title=\"Contour\", ui_name=\"contour\"): vuetify.VSelect( label=\"Contour by\", v_model=(\"contour_by_array_idx\",",
"pipeline # ----------------------------------------------------------------------------- renderer = vtkRenderer() renderWindow = vtkRenderWindow() renderWindow.AddRenderer(renderer)",
"renderer.AddActor(cube_axes) # Cube Axes: Boundaries, camera, and styling cube_axes.SetBounds(mesh_actor.GetBounds()) cube_axes.SetCamera(renderer.GetActiveCamera())",
"dense=True, ) # ----------------------------------------------------------------------------- # GUI # ----------------------------------------------------------------------------- layout =",
"Representation.Points: property.SetRepresentationToPoints() property.SetPointSize(5) property.EdgeVisibilityOff() elif mode == Representation.Wireframe: property.SetRepresentationToWireframe() property.SetPointSize(1)",
"----------------------------------------------------------------------------- # Constants # ----------------------------------------------------------------------------- class Representation: Points = 0",
"GUI # ----------------------------------------------------------------------------- layout = SinglePageWithDrawer(\"Viewer\", on_ready=update_view) layout.title.set_text(\"Viewer\") with layout.toolbar:",
"html_view = remote_view # Update layout layout.content.children[0].children[0] = html_view layout.flush_content()",
"LookupTable.Greyscale: lut.SetHueRange(0.0, 0.0) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(0.0, 1.0) elif preset ==",
"for remote rendering factory initialization, not necessary for # local",
"contour.SetInputArrayToProcess( 0, 0, 0, default_array.get(\"type\"), default_array.get(\"text\") ) contour.SetValue(0, contour_value) #",
"= html_view layout.flush_content() # Update View update_view() # ----------------------------------------------------------------------------- #",
"elif _id == \"2\": # Contour contour_actor.SetVisibility(_visibility) update_view() # -----------------------------------------------------------------------------",
"array.get(\"range\") mapper = actor.GetMapper() mapper.SelectColorArray(array.get(\"text\")) mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") ==",
"elif preset == LookupTable.Inverted_Greyscale: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(0.0, 0.0) lut.SetValueRange(1.0, 0.0)",
"by default array contour_mapper.GetLookupTable().SetRange(default_min, default_max) contour_mapper.SelectColorArray(default_array.get(\"text\")) if default_array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS:",
"== LookupTable.Inverted_Rainbow: lut.SetHueRange(0.0, 0.666) lut.SetSaturationRange(1.0, 1.0) lut.SetValueRange(1.0, 1.0) elif preset",
"----------------------------------------------------------------------------- # Representation Callbacks # ----------------------------------------------------------------------------- def update_representation(actor, mode): property",
"View update_view() @change(\"contour_value\") def update_contour_value(contour_value, **kwargs): contour.SetValue(0, float(contour_value)) update_view() #",
"mapper.GetLookupTable().SetRange(_min, _max) if array.get(\"type\") == vtkDataObject.FIELD_ASSOCIATION_POINTS: mesh_mapper.SetScalarModeToUsePointFieldData() else: mesh_mapper.SetScalarModeToUseCellFieldData() mapper.SetScalarModeToUsePointFieldData()",
"{\"id\": \"2\", \"parent\": \"1\", \"visible\": 1, \"name\": \"Contour\"}, ], ),"
] |
[
"= True if self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z = 0.0",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# Subscribe Infra Red sensors self.subs_right_ir = self.create_subscription( Float64, 'right_IR',",
"# Copyright 1996-2021 Soft_illusion. # # Licensed under the Apache",
"line not seen . if self.ground_right > 500 and self.ground_left",
"the License. import rclpy from rclpy.node import Node from std_msgs.msg",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"2.0 (the \"License\"); # you may not use this file",
"agreed to in writing, software # distributed under the License",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Unless required by applicable law or agreed to in writing,",
"ls = LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown() if __name__ == '__main__':",
"reading variables def right_infrared_callback(self, msg): self.ground_right = msg.data self.lineFollowingModule() def",
"'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1)",
"left_infrared_callback(self, msg): self.ground_left = msg.data def mid_infrared_callback(self, msg): self.ground_mid =",
"= Twist() self.stop = False self.count = 0 self.count_threshold =",
"distributed under the License is distributed on an \"AS IS\"",
"import Twist class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra",
"parameters self.delta = self.ground_right - self.ground_left self.cmd.angular.z = self.angle_correction*self.delta #",
"= 0 if self.count > self.count_threshold: self.stop = True if",
"1) # Publish cmd vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1)",
"Initialize parameters self.ground_right, self.ground_mid, self.ground_left = 0, 0, 0 self.delta",
"self.cmd.angular.z = self.angle_correction*self.delta # Logic for stop if black line",
"self.ground_right - self.ground_left self.cmd.angular.z = self.angle_correction*self.delta # Logic for stop",
"the specific language governing permissions and # limitations under the",
"__init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra Red sensors self.subs_right_ir = self.create_subscription(",
"self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir",
"self.ground_left > 500 and self.ground_mid > 500: self.count += 1",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"super().__init__('linefollower_cmdvel') # Subscribe Infra Red sensors self.subs_right_ir = self.create_subscription( Float64,",
"self.stop = False # Call backs to update sensor reading",
"self.ground_left self.cmd.angular.z = self.angle_correction*self.delta # Logic for stop if black",
"0, 0, 0 self.delta = 0 self.cmd = Twist() self.stop",
"velocity self.cmd.linear.x = self.speed # Correction parameters self.delta = self.ground_right",
"self.ground_right > 500 and self.ground_left > 500 and self.ground_mid >",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"self.count_threshold: self.stop = True if self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z",
"under the License. import rclpy from rclpy.node import Node from",
"except in compliance with the License. # You may obtain",
"governing permissions and # limitations under the License. import rclpy",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"self.speed = 0.2 self.angle_correction = 0.01 # Initialize parameters self.ground_right,",
"# Constant velocity self.cmd.linear.x = self.speed # Correction parameters self.delta",
"lineFollowingModule(self): # Constant velocity self.cmd.linear.x = self.speed # Correction parameters",
"self.ground_mid = msg.data def main(args=None): rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls)",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"rclpy from rclpy.node import Node from std_msgs.msg import Float64 from",
"Correction parameters self.delta = self.ground_right - self.ground_left self.cmd.angular.z = self.angle_correction*self.delta",
"not use this file except in compliance with the License.",
"self.ground_right, self.ground_mid, self.ground_left = 0, 0, 0 self.delta = 0",
"- self.ground_left self.cmd.angular.z = self.angle_correction*self.delta # Logic for stop if",
"Twist() self.stop = False self.count = 0 self.count_threshold = 10",
"msg): self.ground_left = msg.data def mid_infrared_callback(self, msg): self.ground_mid = msg.data",
"from geometry_msgs.msg import Twist class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') #",
"Publish cmd vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1) # vehicle",
"writing, software # distributed under the License is distributed on",
"if self.ground_right > 500 and self.ground_left > 500 and self.ground_mid",
"in writing, software # distributed under the License is distributed",
"> 500: self.count += 1 else: self.count = 0 if",
"cmd vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1) # vehicle parameters",
". if self.ground_right > 500 and self.ground_left > 500 and",
"self.count += 1 else: self.count = 0 if self.count >",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"language governing permissions and # limitations under the License. import",
"def mid_infrared_callback(self, msg): self.ground_mid = msg.data def main(args=None): rclpy.init(args=args) ls",
"False # Call backs to update sensor reading variables def",
"= 0, 0, 0 self.delta = 0 self.cmd = Twist()",
"sensor reading variables def right_infrared_callback(self, msg): self.ground_right = msg.data self.lineFollowingModule()",
"self.mid_infrared_callback, 1) # Publish cmd vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel',",
"self.ground_mid > 500: self.count += 1 else: self.count = 0",
"msg.data def mid_infrared_callback(self, msg): self.ground_mid = msg.data def main(args=None): rclpy.init(args=args)",
"= 10 def lineFollowingModule(self): # Constant velocity self.cmd.linear.x = self.speed",
"and self.ground_left > 500 and self.ground_mid > 500: self.count +=",
"500: self.count += 1 else: self.count = 0 if self.count",
"use this file except in compliance with the License. #",
"self.count = 0 self.count_threshold = 10 def lineFollowingModule(self): # Constant",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"vel self.pubs_cmdvel.publish(self.cmd) self.stop = False # Call backs to update",
"= 0.01 # Initialize parameters self.ground_right, self.ground_mid, self.ground_left = 0,",
"stop if black line not seen . if self.ground_right >",
"seen . if self.ground_right > 500 and self.ground_left > 500",
"import rclpy from rclpy.node import Node from std_msgs.msg import Float64",
"# limitations under the License. import rclpy from rclpy.node import",
"from std_msgs.msg import Float64 from geometry_msgs.msg import Twist class LineFollower(Node):",
"1 else: self.count = 0 if self.count > self.count_threshold: self.stop",
"std_msgs.msg import Float64 from geometry_msgs.msg import Twist class LineFollower(Node): def",
"self.cmd.linear.x = self.speed # Correction parameters self.delta = self.ground_right -",
"self.count = 0 if self.count > self.count_threshold: self.stop = True",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"self.cmd.linear.x = 0.0 self.cmd.angular.z = 0.0 # Publish cmd vel",
"Red sensors self.subs_right_ir = self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"= self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1) # Publish cmd vel",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"def lineFollowingModule(self): # Constant velocity self.cmd.linear.x = self.speed # Correction",
"if black line not seen . if self.ground_right > 500",
"License. # You may obtain a copy of the License",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License, Version 2.0 (the \"License\"); # you may not use",
"# Publish cmd vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1) #",
"vel self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1) # vehicle parameters self.speed",
"self.angle_correction = 0.01 # Initialize parameters self.ground_right, self.ground_mid, self.ground_left =",
"# Initialize parameters self.ground_right, self.ground_mid, self.ground_left = 0, 0, 0",
"Constant velocity self.cmd.linear.x = self.speed # Correction parameters self.delta =",
"# You may obtain a copy of the License at",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"= msg.data def mid_infrared_callback(self, msg): self.ground_mid = msg.data def main(args=None):",
"main(args=None): rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown() if __name__",
"parameters self.speed = 0.2 self.angle_correction = 0.01 # Initialize parameters",
"# Logic for stop if black line not seen .",
"under the License is distributed on an \"AS IS\" BASIS,",
"self.subs_right_ir = self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription(",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"= 0.0 # Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop = False",
"License for the specific language governing permissions and # limitations",
"0, 0 self.delta = 0 self.cmd = Twist() self.stop =",
"self.count_threshold = 10 def lineFollowingModule(self): # Constant velocity self.cmd.linear.x =",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"right_infrared_callback(self, msg): self.ground_right = msg.data self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left",
"Subscribe Infra Red sensors self.subs_right_ir = self.create_subscription( Float64, 'right_IR', self.right_infrared_callback,",
"rclpy.node import Node from std_msgs.msg import Float64 from geometry_msgs.msg import",
"geometry_msgs.msg import Twist class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe",
"= self.speed # Correction parameters self.delta = self.ground_right - self.ground_left",
"0 self.cmd = Twist() self.stop = False self.count = 0",
"if self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z = 0.0 # Publish",
"# Call backs to update sensor reading variables def right_infrared_callback(self,",
"vehicle parameters self.speed = 0.2 self.angle_correction = 0.01 # Initialize",
"500 and self.ground_mid > 500: self.count += 1 else: self.count",
"to update sensor reading variables def right_infrared_callback(self, msg): self.ground_right =",
"0.01 # Initialize parameters self.ground_right, self.ground_mid, self.ground_left = 0, 0,",
"> 500 and self.ground_mid > 500: self.count += 1 else:",
"self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1) #",
"the License for the specific language governing permissions and #",
"def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra Red sensors self.subs_right_ir =",
"= self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription( Float64,",
"self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription( Float64, 'left_IR',",
"# vehicle parameters self.speed = 0.2 self.angle_correction = 0.01 #",
"(the \"License\"); # you may not use this file except",
"0 self.count_threshold = 10 def lineFollowingModule(self): # Constant velocity self.cmd.linear.x",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"limitations under the License. import rclpy from rclpy.node import Node",
"# you may not use this file except in compliance",
"0.0 # Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop = False #",
"either express or implied. # See the License for the",
"def main(args=None): rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown() if",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"permissions and # limitations under the License. import rclpy from",
"'cmd_vel', 1) # vehicle parameters self.speed = 0.2 self.angle_correction =",
"black line not seen . if self.ground_right > 500 and",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"'mid_IR', self.mid_infrared_callback, 1) # Publish cmd vel self.pubs_cmdvel = self.create_publisher(Twist,",
"Infra Red sensors self.subs_right_ir = self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1)",
"1) self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1) # Publish",
"self.delta = 0 self.cmd = Twist() self.stop = False self.count",
"the License is distributed on an \"AS IS\" BASIS, #",
"= False self.count = 0 self.count_threshold = 10 def lineFollowingModule(self):",
"self.cmd.angular.z = 0.0 # Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop =",
"in compliance with the License. # You may obtain a",
"self.speed # Correction parameters self.delta = self.ground_right - self.ground_left self.cmd.angular.z",
"= self.create_publisher(Twist, 'cmd_vel', 1) # vehicle parameters self.speed = 0.2",
"msg.data self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left = msg.data def mid_infrared_callback(self,",
"1) # vehicle parameters self.speed = 0.2 self.angle_correction = 0.01",
"> 500 and self.ground_left > 500 and self.ground_mid > 500:",
"software # distributed under the License is distributed on an",
"Twist class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra Red",
"variables def right_infrared_callback(self, msg): self.ground_right = msg.data self.lineFollowingModule() def left_infrared_callback(self,",
"= self.ground_right - self.ground_left self.cmd.angular.z = self.angle_correction*self.delta # Logic for",
"Call backs to update sensor reading variables def right_infrared_callback(self, msg):",
"Float64 from geometry_msgs.msg import Twist class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel')",
"Float64, 'mid_IR', self.mid_infrared_callback, 1) # Publish cmd vel self.pubs_cmdvel =",
"10 def lineFollowingModule(self): # Constant velocity self.cmd.linear.x = self.speed #",
"Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription( Float64, 'left_IR', self.left_infrared_callback,",
"# # Unless required by applicable law or agreed to",
"self.pubs_cmdvel.publish(self.cmd) self.stop = False # Call backs to update sensor",
"Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback,",
"class LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra Red sensors",
"for stop if black line not seen . if self.ground_right",
"0 if self.count > self.count_threshold: self.stop = True if self.stop:",
"> self.count_threshold: self.stop = True if self.stop: self.cmd.linear.x = 0.0",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1) # Publish cmd",
"self.ground_right = msg.data self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left = msg.data",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop = False # Call backs",
"= msg.data self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left = msg.data def",
"self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left = msg.data def mid_infrared_callback(self, msg):",
"= msg.data def main(args=None): rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls) ls.destroy_node()",
"= LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown() if __name__ == '__main__': main()",
"Version 2.0 (the \"License\"); # you may not use this",
"= self.angle_correction*self.delta # Logic for stop if black line not",
"rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown() if __name__ ==",
"self.cmd = Twist() self.stop = False self.count = 0 self.count_threshold",
"LineFollower(Node): def __init__(self): super().__init__('linefollower_cmdvel') # Subscribe Infra Red sensors self.subs_right_ir",
"from rclpy.node import Node from std_msgs.msg import Float64 from geometry_msgs.msg",
"self.create_subscription( Float64, 'mid_IR', self.mid_infrared_callback, 1) # Publish cmd vel self.pubs_cmdvel",
"self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z = 0.0 # Publish cmd",
"law or agreed to in writing, software # distributed under",
"= 0 self.cmd = Twist() self.stop = False self.count =",
"False self.count = 0 self.count_threshold = 10 def lineFollowingModule(self): #",
"mid_infrared_callback(self, msg): self.ground_mid = msg.data def main(args=None): rclpy.init(args=args) ls =",
"0 self.delta = 0 self.cmd = Twist() self.stop = False",
"Soft_illusion. # # Licensed under the Apache License, Version 2.0",
"update sensor reading variables def right_infrared_callback(self, msg): self.ground_right = msg.data",
"True if self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z = 0.0 #",
"implied. # See the License for the specific language governing",
"self.count > self.count_threshold: self.stop = True if self.stop: self.cmd.linear.x =",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"1996-2021 Soft_illusion. # # Licensed under the Apache License, Version",
"\"License\"); # you may not use this file except in",
"= False # Call backs to update sensor reading variables",
"= 0.0 self.cmd.angular.z = 0.0 # Publish cmd vel self.pubs_cmdvel.publish(self.cmd)",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"import Float64 from geometry_msgs.msg import Twist class LineFollower(Node): def __init__(self):",
"# Correction parameters self.delta = self.ground_right - self.ground_left self.cmd.angular.z =",
"self.angle_correction*self.delta # Logic for stop if black line not seen",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"self.pubs_cmdvel = self.create_publisher(Twist, 'cmd_vel', 1) # vehicle parameters self.speed =",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"'right_IR', self.right_infrared_callback, 1) self.subs_left_ir = self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1)",
"parameters self.ground_right, self.ground_mid, self.ground_left = 0, 0, 0 self.delta =",
"0.0 self.cmd.angular.z = 0.0 # Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop",
"self.stop = True if self.stop: self.cmd.linear.x = 0.0 self.cmd.angular.z =",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"1) self.subs_left_ir = self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir =",
"and # limitations under the License. import rclpy from rclpy.node",
"= 0.2 self.angle_correction = 0.01 # Initialize parameters self.ground_right, self.ground_mid,",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"self.stop = False self.count = 0 self.count_threshold = 10 def",
"msg): self.ground_mid = msg.data def main(args=None): rclpy.init(args=args) ls = LineFollower()",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# See the License for the specific language governing permissions",
"def left_infrared_callback(self, msg): self.ground_left = msg.data def mid_infrared_callback(self, msg): self.ground_mid",
"You may obtain a copy of the License at #",
"import Node from std_msgs.msg import Float64 from geometry_msgs.msg import Twist",
"if self.count > self.count_threshold: self.stop = True if self.stop: self.cmd.linear.x",
"self.subs_left_ir = self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription(",
"msg.data def main(args=None): rclpy.init(args=args) ls = LineFollower() rclpy.spin(ls) ls.destroy_node() rclpy.shutdown()",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"Node from std_msgs.msg import Float64 from geometry_msgs.msg import Twist class",
"Copyright 1996-2021 Soft_illusion. # # Licensed under the Apache License,",
"self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription( Float64, 'mid_IR',",
"self.ground_left = 0, 0, 0 self.delta = 0 self.cmd =",
"msg): self.ground_right = msg.data self.lineFollowingModule() def left_infrared_callback(self, msg): self.ground_left =",
"required by applicable law or agreed to in writing, software",
"cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop = False # Call backs to",
"+= 1 else: self.count = 0 if self.count > self.count_threshold:",
"self.ground_left = msg.data def mid_infrared_callback(self, msg): self.ground_mid = msg.data def",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"License. import rclpy from rclpy.node import Node from std_msgs.msg import",
"500 and self.ground_left > 500 and self.ground_mid > 500: self.count",
"self.delta = self.ground_right - self.ground_left self.cmd.angular.z = self.angle_correction*self.delta # Logic",
"def right_infrared_callback(self, msg): self.ground_right = msg.data self.lineFollowingModule() def left_infrared_callback(self, msg):",
"with the License. # You may obtain a copy of",
"self.ground_mid, self.ground_left = 0, 0, 0 self.delta = 0 self.cmd",
"this file except in compliance with the License. # You",
"= self.create_subscription( Float64, 'left_IR', self.left_infrared_callback, 1) self.subs_mid_ir = self.create_subscription( Float64,",
"self.create_publisher(Twist, 'cmd_vel', 1) # vehicle parameters self.speed = 0.2 self.angle_correction",
"= 0 self.count_threshold = 10 def lineFollowingModule(self): # Constant velocity",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"backs to update sensor reading variables def right_infrared_callback(self, msg): self.ground_right",
"else: self.count = 0 if self.count > self.count_threshold: self.stop =",
"# Publish cmd vel self.pubs_cmdvel.publish(self.cmd) self.stop = False # Call",
"0.2 self.angle_correction = 0.01 # Initialize parameters self.ground_right, self.ground_mid, self.ground_left",
"and self.ground_mid > 500: self.count += 1 else: self.count =",
"sensors self.subs_right_ir = self.create_subscription( Float64, 'right_IR', self.right_infrared_callback, 1) self.subs_left_ir =",
"not seen . if self.ground_right > 500 and self.ground_left >",
"Logic for stop if black line not seen . if"
] |
[
"'3306', } if __name__ == \"__main__\": try: conn = mysql.connector.connect(**config)",
"+ str(row[1])) conn.close() except mysql.connector.Error as err: if err.errno ==",
"wrong with your user name or password\") elif err.errno ==",
"user name or password\") elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does",
"from mysql.connector import errorcode config = { 'user': 'user', 'password':",
"'mysql_container', 'database': 'sample_db', 'port': '3306', } if __name__ == \"__main__\":",
"== \"__main__\": try: conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select",
"mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select * from users') for row",
"+ str(row[0]) + \"\" + \"time_zone_id\" + str(row[1])) conn.close() except",
"is wrong with your user name or password\") elif err.errno",
"except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is",
"mysql.connector import errorcode config = { 'user': 'user', 'password': 'password',",
"= mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select * from users') for",
"cursor = conn.cursor() cursor.execute('select * from users') for row in",
"users') for row in cursor.fetchall(): print(\"name:\" + str(row[0]) + \"\"",
"for row in cursor.fetchall(): print(\"name:\" + str(row[0]) + \"\" +",
"cursor.execute('select * from users') for row in cursor.fetchall(): print(\"name:\" +",
"name or password\") elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does not",
"print(\"Something is wrong with your user name or password\") elif",
"== errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with your user name or",
"} if __name__ == \"__main__\": try: conn = mysql.connector.connect(**config) cursor",
"\"time_zone_id\" + str(row[1])) conn.close() except mysql.connector.Error as err: if err.errno",
"err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with your",
"your user name or password\") elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database",
"or password\") elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does not exist\")",
"password\") elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does not exist\") else:",
"'user', 'password': 'password', 'host': 'mysql_container', 'database': 'sample_db', 'port': '3306', }",
"print(\"name:\" + str(row[0]) + \"\" + \"time_zone_id\" + str(row[1])) conn.close()",
"from users') for row in cursor.fetchall(): print(\"name:\" + str(row[0]) +",
"err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with your user name",
"conn.close() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something",
"if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with your user",
"row in cursor.fetchall(): print(\"name:\" + str(row[0]) + \"\" + \"time_zone_id\"",
"+ \"\" + \"time_zone_id\" + str(row[1])) conn.close() except mysql.connector.Error as",
"{ 'user': 'user', 'password': 'password', 'host': 'mysql_container', 'database': 'sample_db', 'port':",
"+ \"time_zone_id\" + str(row[1])) conn.close() except mysql.connector.Error as err: if",
"import mysql.connector from mysql.connector import errorcode config = { 'user':",
"= { 'user': 'user', 'password': 'password', 'host': 'mysql_container', 'database': 'sample_db',",
"elif err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does not exist\") else: print(err)",
"try: conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select * from",
"err.errno == errorcode.ER_BAD_DB_ERROR: print(\"Database does not exist\") else: print(err) else:",
"'database': 'sample_db', 'port': '3306', } if __name__ == \"__main__\": try:",
"as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with",
"conn.cursor() cursor.execute('select * from users') for row in cursor.fetchall(): print(\"name:\"",
"if __name__ == \"__main__\": try: conn = mysql.connector.connect(**config) cursor =",
"'user': 'user', 'password': 'password', 'host': 'mysql_container', 'database': 'sample_db', 'port': '3306',",
"\"\" + \"time_zone_id\" + str(row[1])) conn.close() except mysql.connector.Error as err:",
"cursor.fetchall(): print(\"name:\" + str(row[0]) + \"\" + \"time_zone_id\" + str(row[1]))",
"str(row[1])) conn.close() except mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:",
"with your user name or password\") elif err.errno == errorcode.ER_BAD_DB_ERROR:",
"== errorcode.ER_BAD_DB_ERROR: print(\"Database does not exist\") else: print(err) else: conn.close()",
"'password': 'password', 'host': 'mysql_container', 'database': 'sample_db', 'port': '3306', } if",
"'port': '3306', } if __name__ == \"__main__\": try: conn =",
"= conn.cursor() cursor.execute('select * from users') for row in cursor.fetchall():",
"in cursor.fetchall(): print(\"name:\" + str(row[0]) + \"\" + \"time_zone_id\" +",
"mysql.connector.Error as err: if err.errno == errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong",
"\"__main__\": try: conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select *",
"config = { 'user': 'user', 'password': 'password', 'host': 'mysql_container', 'database':",
"'password', 'host': 'mysql_container', 'database': 'sample_db', 'port': '3306', } if __name__",
"* from users') for row in cursor.fetchall(): print(\"name:\" + str(row[0])",
"import errorcode config = { 'user': 'user', 'password': 'password', 'host':",
"mysql.connector from mysql.connector import errorcode config = { 'user': 'user',",
"conn = mysql.connector.connect(**config) cursor = conn.cursor() cursor.execute('select * from users')",
"errorcode.ER_ACCESS_DENIED_ERROR: print(\"Something is wrong with your user name or password\")",
"'host': 'mysql_container', 'database': 'sample_db', 'port': '3306', } if __name__ ==",
"'sample_db', 'port': '3306', } if __name__ == \"__main__\": try: conn",
"errorcode config = { 'user': 'user', 'password': 'password', 'host': 'mysql_container',",
"__name__ == \"__main__\": try: conn = mysql.connector.connect(**config) cursor = conn.cursor()",
"str(row[0]) + \"\" + \"time_zone_id\" + str(row[1])) conn.close() except mysql.connector.Error"
] |
[
"tinta # seriam necessários para a pintura, após perguntar o",
"é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para pintar toda a",
"em metros: ')) largura = float(input('Informe a largura da parede",
"um programa que pergunte as dimensões de uma parede, calcule",
"/ litros print('\\nSe a lata possui {:.2f}L e rende {:.2f}m²'.format(litros,",
"área e informe quantos litros de tinta # seriam necessários",
"print('\\nSe a lata possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata)) print('então",
"da tinta informado na lata print('=' * 40) print('{:^40}'.format('Assistente de",
"float(input('\\nQuantos litros contém a lata de tinta escolhida? ')) rendlata",
"rendlata / litros print('\\nSe a lata possui {:.2f}L e rende",
"a largura da parede em metros: ')) area = altura",
"* 40) altura = float(input('Informe a altura da parede em",
"da parede em metros: ')) largura = float(input('Informe a largura",
"sua área e informe quantos litros de tinta # seriam",
"informado na lata? ')) rendlitro = rendlata / litros print('\\nSe",
"litros contém a lata de tinta escolhida? ')) rendlata =",
"altura = float(input('Informe a altura da parede em metros: '))",
"criar um programa que pergunte as dimensões de uma parede,",
"a pintura, após perguntar o rendimento da tinta informado na",
"= float(input('Informe a largura da parede em metros: ')) area",
"lata print('=' * 40) print('{:^40}'.format('Assistente de pintura')) print('=' * 40)",
"uma parede, calcule sua área e informe quantos litros de",
"float(input('Informe a altura da parede em metros: ')) largura =",
"tinta escolhida? ')) rendlata = float(input('Qual o rendimento em metros",
"print('=' * 40) print('{:^40}'.format('Assistente de pintura')) print('=' * 40) altura",
"rende {:.2f}m²'.format(litros, rendlata)) print('então o rendimento por litro é de",
"')) area = altura * largura print('\\nA área total da",
"= float(input('\\nQuantos litros contém a lata de tinta escolhida? '))",
"{:.2f}m²'.format(litros, rendlata)) print('então o rendimento por litro é de {:.2f}m²'.format(rendlitro))",
"rendlitro = rendlata / litros print('\\nSe a lata possui {:.2f}L",
"por litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para pintar",
"rendimento por litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para",
"de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para pintar toda a parede'.format(area",
"parede, calcule sua área e informe quantos litros de tinta",
"rendimento da tinta informado na lata print('=' * 40) print('{:^40}'.format('Assistente",
"')) rendlata = float(input('Qual o rendimento em metros informado na",
"o rendimento em metros informado na lata? ')) rendlitro =",
"lata de tinta escolhida? ')) rendlata = float(input('Qual o rendimento",
"litros de tinta # seriam necessários para a pintura, após",
"{:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros contém a lata de tinta",
"a lata possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata)) print('então o",
"o rendimento por litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L",
"metros informado na lata? ')) rendlitro = rendlata / litros",
"informado na lata print('=' * 40) print('{:^40}'.format('Assistente de pintura')) print('='",
"na lata print('=' * 40) print('{:^40}'.format('Assistente de pintura')) print('=' *",
"de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros contém a lata de",
"{:.2f}L e rende {:.2f}m²'.format(litros, rendlata)) print('então o rendimento por litro",
"print('\\nA área total da parede é de {:.2f}m²'.format(area)) litros =",
"parede em metros: ')) largura = float(input('Informe a largura da",
"* largura print('\\nA área total da parede é de {:.2f}m²'.format(area))",
"na lata? ')) rendlitro = rendlata / litros print('\\nSe a",
"litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para pintar toda",
"tinta informado na lata print('=' * 40) print('{:^40}'.format('Assistente de pintura'))",
"que pergunte as dimensões de uma parede, calcule sua área",
"pintura, após perguntar o rendimento da tinta informado na lata",
"parede é de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros contém a",
"# seriam necessários para a pintura, após perguntar o rendimento",
"contém a lata de tinta escolhida? ')) rendlata = float(input('Qual",
"area = altura * largura print('\\nA área total da parede",
"pergunte as dimensões de uma parede, calcule sua área e",
"# criar um programa que pergunte as dimensões de uma",
"= rendlata / litros print('\\nSe a lata possui {:.2f}L e",
"da parede é de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros contém",
"possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata)) print('então o rendimento por",
"em metros informado na lata? ')) rendlitro = rendlata /",
"* 40) print('{:^40}'.format('Assistente de pintura')) print('=' * 40) altura =",
"a altura da parede em metros: ')) largura = float(input('Informe",
"informe quantos litros de tinta # seriam necessários para a",
"print('{:^40}'.format('Assistente de pintura')) print('=' * 40) altura = float(input('Informe a",
"seriam necessários para a pintura, após perguntar o rendimento da",
"lata? ')) rendlitro = rendlata / litros print('\\nSe a lata",
"altura da parede em metros: ')) largura = float(input('Informe a",
"em metros: ')) area = altura * largura print('\\nA área",
"')) largura = float(input('Informe a largura da parede em metros:",
"pintura')) print('=' * 40) altura = float(input('Informe a altura da",
"metros: ')) largura = float(input('Informe a largura da parede em",
"necessários para a pintura, após perguntar o rendimento da tinta",
"total da parede é de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros",
"escolhida? ')) rendlata = float(input('Qual o rendimento em metros informado",
"= float(input('Qual o rendimento em metros informado na lata? '))",
"40) altura = float(input('Informe a altura da parede em metros:",
"da parede em metros: ')) area = altura * largura",
"float(input('Qual o rendimento em metros informado na lata? ')) rendlitro",
"= altura * largura print('\\nA área total da parede é",
"após perguntar o rendimento da tinta informado na lata print('='",
"largura da parede em metros: ')) area = altura *",
"litros = float(input('\\nQuantos litros contém a lata de tinta escolhida?",
"área total da parede é de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos",
"dimensões de uma parede, calcule sua área e informe quantos",
"para a pintura, após perguntar o rendimento da tinta informado",
"largura = float(input('Informe a largura da parede em metros: '))",
"e rende {:.2f}m²'.format(litros, rendlata)) print('então o rendimento por litro é",
"de tinta escolhida? ')) rendlata = float(input('Qual o rendimento em",
"calcule sua área e informe quantos litros de tinta #",
"e informe quantos litros de tinta # seriam necessários para",
"print('=' * 40) altura = float(input('Informe a altura da parede",
"largura print('\\nA área total da parede é de {:.2f}m²'.format(area)) litros",
"litros print('\\nSe a lata possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata))",
"perguntar o rendimento da tinta informado na lata print('=' *",
"rendimento em metros informado na lata? ')) rendlitro = rendlata",
"40) print('{:^40}'.format('Assistente de pintura')) print('=' * 40) altura = float(input('Informe",
"de uma parede, calcule sua área e informe quantos litros",
"de pintura')) print('=' * 40) altura = float(input('Informe a altura",
"float(input('Informe a largura da parede em metros: ')) area =",
"metros: ')) area = altura * largura print('\\nA área total",
"rendlata = float(input('Qual o rendimento em metros informado na lata?",
"as dimensões de uma parede, calcule sua área e informe",
"rendlata)) print('então o rendimento por litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão",
"= float(input('Informe a altura da parede em metros: ')) largura",
"a lata de tinta escolhida? ')) rendlata = float(input('Qual o",
"quantos litros de tinta # seriam necessários para a pintura,",
"')) rendlitro = rendlata / litros print('\\nSe a lata possui",
"{:.2f}m²'.format(rendlitro)) print('\\nSerão necessário {:.2f}L para pintar toda a parede'.format(area /",
"altura * largura print('\\nA área total da parede é de",
"parede em metros: ')) area = altura * largura print('\\nA",
"lata possui {:.2f}L e rende {:.2f}m²'.format(litros, rendlata)) print('então o rendimento",
"programa que pergunte as dimensões de uma parede, calcule sua",
"o rendimento da tinta informado na lata print('=' * 40)",
"de tinta # seriam necessários para a pintura, após perguntar",
"é de {:.2f}m²'.format(area)) litros = float(input('\\nQuantos litros contém a lata",
"print('\\nSerão necessário {:.2f}L para pintar toda a parede'.format(area / rendlitro))",
"print('então o rendimento por litro é de {:.2f}m²'.format(rendlitro)) print('\\nSerão necessário"
] |
[
"from random import sample from time import sleep jogos =",
"') print('-=' * 3) for i in range(n): jogos.append(sample(range(1,61), 6))",
"int(input(\"\\nQuatos jogos você quer que eu sorteie? \")) if (n",
"jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-=' * 5, end='",
"(n > 0): break print('\\n[ERRO] Valor fora do intervalo') print()",
"print() print('-=' * 3, end=' ') print(f'SORTEANDO {n} JOGOS', end='",
"') print('< BOA SORTE >', end=' ') print('-=' * 3,",
"end=' ') print('< BOA SORTE >', end=' ') print('-=' *",
"SENA\":^20}') print('-' * 20) while True: n = int(input(\"\\nQuatos jogos",
"print('-' * 20) print(f'{\"MEGA SENA\":^20}') print('-' * 20) while True:",
"eu sorteie? \")) if (n > 0): break print('\\n[ERRO] Valor",
"if (n > 0): break print('\\n[ERRO] Valor fora do intervalo')",
"* 3) for i in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo",
"n = int(input(\"\\nQuatos jogos você quer que eu sorteie? \"))",
"intervalo') print() print('-=' * 3, end=' ') print(f'SORTEANDO {n} JOGOS',",
"print('-=' * 3, end=' ') print(f'SORTEANDO {n} JOGOS', end=' ')",
"for i in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}')",
"3) for i in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}:",
"i in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-='",
"fora do intervalo') print() print('-=' * 3, end=' ') print(f'SORTEANDO",
"print(f'SORTEANDO {n} JOGOS', end=' ') print('-=' * 3) for i",
"* 20) while True: n = int(input(\"\\nQuatos jogos você quer",
"sample from time import sleep jogos = list() print('-' *",
"= int(input(\"\\nQuatos jogos você quer que eu sorteie? \")) if",
"time import sleep jogos = list() print('-' * 20) print(f'{\"MEGA",
"sorteie? \")) if (n > 0): break print('\\n[ERRO] Valor fora",
"break print('\\n[ERRO] Valor fora do intervalo') print() print('-=' * 3,",
"while True: n = int(input(\"\\nQuatos jogos você quer que eu",
"{jogos[i]}') print('-=' * 5, end=' ') print('< BOA SORTE >',",
"import sleep jogos = list() print('-' * 20) print(f'{\"MEGA SENA\":^20}')",
"list() print('-' * 20) print(f'{\"MEGA SENA\":^20}') print('-' * 20) while",
"> 0): break print('\\n[ERRO] Valor fora do intervalo') print() print('-='",
"') print(f'SORTEANDO {n} JOGOS', end=' ') print('-=' * 3) for",
"= list() print('-' * 20) print(f'{\"MEGA SENA\":^20}') print('-' * 20)",
"6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-=' * 5, end=' ')",
"você quer que eu sorteie? \")) if (n > 0):",
"3, end=' ') print(f'SORTEANDO {n} JOGOS', end=' ') print('-=' *",
"print(f'{\"MEGA SENA\":^20}') print('-' * 20) while True: n = int(input(\"\\nQuatos",
"do intervalo') print() print('-=' * 3, end=' ') print(f'SORTEANDO {n}",
"from time import sleep jogos = list() print('-' * 20)",
"que eu sorteie? \")) if (n > 0): break print('\\n[ERRO]",
"Valor fora do intervalo') print() print('-=' * 3, end=' ')",
"print('-=' * 3) for i in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6)",
"sleep jogos = list() print('-' * 20) print(f'{\"MEGA SENA\":^20}') print('-'",
"* 20) print(f'{\"MEGA SENA\":^20}') print('-' * 20) while True: n",
"sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-=' * 5, end=' ') print('<",
"5, end=' ') print('< BOA SORTE >', end=' ') print('-='",
"random import sample from time import sleep jogos = list()",
"{i+1}: {jogos[i]}') print('-=' * 5, end=' ') print('< BOA SORTE",
"print(f'Jogo {i+1}: {jogos[i]}') print('-=' * 5, end=' ') print('< BOA",
"0): break print('\\n[ERRO] Valor fora do intervalo') print() print('-=' *",
"print('\\n[ERRO] Valor fora do intervalo') print() print('-=' * 3, end='",
"jogos = list() print('-' * 20) print(f'{\"MEGA SENA\":^20}') print('-' *",
"20) print(f'{\"MEGA SENA\":^20}') print('-' * 20) while True: n =",
"print('-=' * 5, end=' ') print('< BOA SORTE >', end='",
"in range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-=' *",
"{n} JOGOS', end=' ') print('-=' * 3) for i in",
"JOGOS', end=' ') print('-=' * 3) for i in range(n):",
"import sample from time import sleep jogos = list() print('-'",
"end=' ') print(f'SORTEANDO {n} JOGOS', end=' ') print('-=' * 3)",
"20) while True: n = int(input(\"\\nQuatos jogos você quer que",
"quer que eu sorteie? \")) if (n > 0): break",
"* 3, end=' ') print(f'SORTEANDO {n} JOGOS', end=' ') print('-='",
"end=' ') print('-=' * 3) for i in range(n): jogos.append(sample(range(1,61),",
"True: n = int(input(\"\\nQuatos jogos você quer que eu sorteie?",
"print('-' * 20) while True: n = int(input(\"\\nQuatos jogos você",
"jogos você quer que eu sorteie? \")) if (n >",
"\")) if (n > 0): break print('\\n[ERRO] Valor fora do",
"range(n): jogos.append(sample(range(1,61), 6)) sleep(0.6) print(f'Jogo {i+1}: {jogos[i]}') print('-=' * 5,",
"* 5, end=' ') print('< BOA SORTE >', end=' ')",
"print('< BOA SORTE >', end=' ') print('-=' * 3, end='\\n\\n')"
] |
[
"type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer( 'SECURED', views.protected_view_by_role,",
"expected = u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"= [MockPattern()] self.regex = MockRegexResolver() self.app_name = 'fake-app-name' self.namespace =",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, 'fake-callback',",
"assert 'fake-app-3' not in result class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url",
"used: neither decorator, ' expected += u'mixin, or middleware.' def",
"test_detect_access_is_not_by_role( self, mock_view_access ): expected = u'' mock_view_access.type = 'pu'",
"def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT",
"MockRegex: def __init__(self): self.pattern = '^fake-regex-pattern/$' class MockRegexResolver: def __init__(self):",
"test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' + NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result,",
"= '^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace =",
"mock_view_access.roles.all.return_value = [role_1, role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def",
"def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report')",
"def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result",
"def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None]",
"'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver =",
"test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported:",
"= u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected)",
"'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected =",
"Django role access tool is used: neither ' expected +=",
"mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c', 'd', 'e')]",
"u'fake-app-name' app_type = None view_list = ['fake-view-list'] expected = u'fake-app-name,no",
"self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS())",
"self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ):",
"type='br') role_1, created = Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1)",
"1) def test_cvs_format_write_footer_to_string(self): expected = u'\\n' self._output.set_format('csv') self._output.write_footer() self.assertEqual(self._output._row, expected)",
"function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view')",
"test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type By role.'",
"information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self ): expected",
"test_without_middleware_with_view_access_object_authorized(self): expected = u'View access is of type Authorized.' ViewAccess.objects.create(",
"'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverNested() result = walk_site_url([self.pattern_1,",
"role-2' view_access = ViewAccess.objects.create(view='any-name', type='br') role_1, created = Group.objects.get_or_create(name='role-1') role_2,",
"'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver =",
"@access_by_role def function(): pass view_access = Mock() view_access.type = 'pu'",
"'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data =",
"is used: neither ' expected += 'decorator, mixin, or middleware.'",
"expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report')",
"expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected = u'\\t' +",
"self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-none' class",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('Authorized', function, 'fake-view-name', False)",
"= MockResolverDjango2None2() # result = walk_site_url([resolver]) # print(result) # self.assertEqual(result,",
"def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback =",
"'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() result =",
"TestCase as UnitTestCase from django.contrib.auth.models import Group from django.core.management import",
"IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected = u'ERROR: No roles configured to",
"= MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self):",
"self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected = u'View access is of",
"type='au') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected)",
"test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report')",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def",
"self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self ): expected = u'\\t' +",
"def test_report_for_no_application_type(self): expected = u'\\t' + NONE_TYPE_DEFAULT result = get_view_analyze_report(None)",
"\\ u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self):",
"test_without_middleware_with_view_access_object(self): expected = u'View access is of type By role.'",
"fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected = u''",
"as e: OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format == 'console' def",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type = u'fake-app-type'",
"= get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self,",
"test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data",
"result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def",
"text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def",
"test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected = u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value",
"None)] expected_result = [('a1', 'b2', 'c3')] result = get_views_by_app(data) self.assertEqual(expected_result,",
"'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style =",
"expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) expected += u'\\t\\t{}",
"self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected = u'View access is of",
"roles access tool used. Access to view depends ' expected",
"self.url_patterns = [MockPatternDjango2None()] self.app_name = None self.namespace = None class",
"self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some",
"def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected = u'\\t' + NONE_TYPE_DEFAULT",
"('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockResolver(), MockResolverNested()])",
"def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data = [('a',",
"= 'fake-app-name' self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1",
"1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected = u'Django roles access",
"= None view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected",
"expected = u'View access is of type Public.' @access_by_role def",
"= 'fake-callback' self.name = 'fake-view-none' class MockResolverDjango2: def __init__(self): self.pattern",
"test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type =",
"__init__(self): self.url_patterns = [MockPattern()] self.regex = MockRegexResolver() self.app_name = 'fake-app-name'",
"self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT @access_by_role def",
"test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type = None view_list = ['fake-view']",
"from tests import views from django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer,",
"def test_without_middleware_with_view_access_object_authorized(self): expected = u'View access is of type Authorized.'",
"app_type = u'fake-app-type' view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name)",
"get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport)",
"= analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No",
"function(): pass view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value =",
"g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1)",
"Group from django.core.management import BaseCommand from django.conf import settings from",
"self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access = Mock()",
"list) def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name',",
"False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access is",
"def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result =",
"access is of type By role.' expected += u'Roles with",
"expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected = u'Roles with",
"def __init__(self): self.regex = MockRegex() self.callback = 'fake-callback' self.name =",
"test_detect_access_is_by_role(self): expected = u'ERROR: No roles configured to access de",
"MockRegexResolver: def __init__(self): self.pattern = '^fake-resolver/' class MockRegexResolverNested: def __init__(self):",
"app_type = None view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name)",
"class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name',",
"'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase):",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active')",
"= view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role(",
"self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert",
"walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/',",
"text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected = u'Start checking views",
"result assert 'fake-app-2' in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings",
"self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected = u'View access",
"def test_detect_access_is_by_role( self, mock_view_access ): expected = u'ERROR: No roles",
"report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake",
"'fake-app-name' ) ] resolver = MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver])",
"None result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def",
"role_2.name = u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2] result = analyze_by_role(mock_view_access)",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', function,",
"e: OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format == 'console' def test_set_format(self):",
"test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view']",
"= 'fake-view-name' class MockPatternDjango2None: def __init__(self): self.pattern = '^fake-pattern/' self.callback",
"get_views_by_app(self.data) assert 'fake-app-1' in result assert 'fake-app-2' in result @patch('django_roles_access.utils.settings')",
"roles configured to access de view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value",
"): expected = u'\\t' + NONE_TYPE_DEFAULT result = view_access_analyzer( None,",
"test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT @access_by_role",
"get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS",
"'protected_by_role', 'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\"",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access(",
"expected_result = [('a', 'b', 'c')] result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1'])",
"mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings')",
"expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result,",
"= walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role,",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self,",
"app_type) expected += u'\\t\\t{} does not have configured views.'.format(app_name) self._output.process_application_data(app_name,",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected",
"test_without_middleware_with_view_access_object_public(self): expected = u'View access is of type Public.' ViewAccess.objects.create(",
"result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode) except:",
"): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format = 'csv'",
"'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS",
"view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected = u'\\t'",
"'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view(",
"), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2()",
"None result = view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def",
"False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self ): expected = u'\\t'",
"self._output = OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self):",
"self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name = u'fake-view-name' url",
"== self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and self._output._row ==",
"= u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"mock_objects ): expected = u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects",
"type='pu') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected)",
"+ NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer(",
"is of type Public.' view_access = Mock() view_access.type = 'pu'",
"'2', '3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a1',",
"self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected",
"mock_objects ): expected = u'View access is of type Public.'",
"access middleware is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"expected_result = [ # ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None #",
"def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' + NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED')",
"self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data)",
"mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access = Mock() view_access.type",
"test_no_django_roles_tools_used_application_type( self, mock_objects ): expected = u'No Django roles access",
"= u'ERROR: View access object exist for the view, but",
"u'fake-view-name' url = '/fake-url/' expected = u'\\n\\t\\tAnalysis for view: {}'.format(view_name)",
"+= u'mixin, or middleware.' def function(): pass view_access = Mock()",
"test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected = u'No Django roles access",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"= [] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is",
"import Group from django.core.management import BaseCommand from django.conf import settings",
"u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type",
"class MockResolverDjangoNested: def __init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()]",
"self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout =",
"= walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [",
"object exist for the view, ' expected += 'but no",
"__init__(self): self.url_patterns = [MockResolver()] self.regex = MockRegexResolverNested() self.app_name = 'fake-app-name'",
"result = get_views_by_app(self.data) assert 'fake-app-1' in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element(",
"= u'Roles with access: role-1, role-2' view_access = ViewAccess.objects.create(view='any-name', type='br')",
"NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex: def __init__(self):",
"mock_objects ): expected = u'ERROR: View access object exist for",
"expected += u'mixin, or middleware.' def function(): pass view_access =",
"def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row,",
"'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected",
"test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role,",
"expected = u'End checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"'/fake-url/' expected = u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected += u'\\n\\t\\tView",
"test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type = None view_list = ['fake-view-list']",
"mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True)",
"= u'Start checking views access.\\n' expected += u'Start gathering information.'",
"'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result",
"= ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) assert 'fake-app-1' in result",
"Mock() role_1.name = u'role-1' role_2 = Mock() role_2.name = u'role-2'",
"= u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED',",
"'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected =",
"have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"= u'' mock_view_access.type = 'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result, expected)",
"access object exist for the view, ' expected += 'but",
"test_default_output_format_is_correct_type(self): assert self._output._format == 'console' def test_set_format(self): self._output.set_format('csv') assert self._output._format",
"= ['fake-app-1'] data = [('a', 'b', 'c', 'd', 'e')] with",
"'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver =",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role')",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ):",
"view_list = [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list)",
"expected = u'' view_access = ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access)",
"('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result = walk_site_url(self.url) self.assertIn(expected_result, result) def",
"self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format",
"u'View access is of type Public.' view_access = Mock() view_access.type",
"expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ): view_access =",
"'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result =",
"app_type = None view_list = ['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name)",
"= '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-name' class MockPatternDjango2None:",
"UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects ): view_access = Mock() view_access.type",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called",
"mock_objects.first.return_value = None result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' +",
"= Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2] result",
"= get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role,",
"test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,')",
"test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a',",
"'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result)",
"def test_report_for_application_type_SECURED(self): expected = u'\\t' + SECURED_DEFAULT result = get_view_analyze_report('SECURED')",
"of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer( 'SECURED',",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,'",
"import import_module from unittest import TestCase as UnitTestCase from django.contrib.auth.models",
"IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' + SECURED_DEFAULT result =",
"def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url))",
"'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ]",
"is used: neither decorator, ' expected += u'mixin, or middleware.'",
"@patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2']",
"('a1', 'b2', 'c3', None)] expected_result = [('a1', 'b2', 'c3')] result",
"['fake-app-1', 'fake-app-2', None] data = [('a', 'b', 'c', 'fake-app-1'), ('1',",
"to view depends ' expected += u'on its implementation.' def",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count,",
"view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects",
"'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected =",
"of type Public.' @access_by_role def function(): pass view_access = Mock()",
"def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ):",
"+ DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected",
"view_list = ['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type,",
"('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ]",
"test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected =",
"'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver =",
"'br' mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) class",
"expected = u'No Django roles access tool used. Access to",
"with self.assertRaises(TypeError) as e: OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format ==",
"'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n'",
"= u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) # View_access_analyzer",
"decorator, ' expected += u'mixin, or middleware.' def function(): pass",
"u'ERROR: No roles configured to access de view.' mock_view_access.type =",
"u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name,",
"= view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self):",
"('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverNested() result",
"'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver = MockResolver()",
"self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some",
"u'Roles with access: role-1, role-2' view_access = ViewAccess.objects.create(view='any-name', type='br') role_1,",
"walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name',",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c')]",
"'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result,",
"mock_objects.first.return_value = None result = view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result,",
"access object exist for the view, but no ' expected",
"expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def",
"= None result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"@patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv')",
"result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result =",
"('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' )",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'],",
"= None result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"MockResolverDjangoNested: def __init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name",
"get_views_by_app(self.data) assert 'fake-app-3' not in result class IntegratedTestGetViewsByApp(TestCase): def setUp(self):",
"self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report')",
"+ NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected",
"used: neither ' expected += 'decorator, mixin, or middleware.' ViewAccess.objects.create(",
"): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c', 'd',",
"self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected = u'View",
"('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self):",
"= view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result,",
"configured to access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result =",
"'decorator, mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer(",
"No roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br')",
"= [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name'",
"): expected = u'Django roles access middleware is active: False.\\n'",
"= 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected",
"'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 = MockPattern() self.data =",
"'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result)",
"tests import views from django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report,",
"= u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au')",
"return a dictionary with keys been installed applications. \"\"\" def",
"self.namespace = None class MockResolverDjango2None2: def __init__(self): self.pattern = '^fake-resolver/'",
"view_access.save() result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected =",
"def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/',",
"def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type",
"print(result) # self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url =",
"= [('a', 'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element(",
"of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer( 'SECURED',",
"expected = u'Django roles access middleware is active: False.\\n' self._output.set_format('csv')",
"self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def",
"url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url",
"Django roles access tool used. Access to view depends '",
"self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview))",
"= 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjango2None: def __init__(self): self.pattern",
"analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected =",
"get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role')",
"result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected",
"check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class",
"'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver",
"= view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def",
"'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected",
"= 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format =",
"u'End checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self):",
"fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected = u'Django",
"expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None),",
"Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result",
"function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ):",
"self._output._format == 'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other',",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once(",
"test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result = walk_site_url(self.url)",
"view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"'fake-view-name' class MockResolver: def __init__(self): self.url_patterns = [MockPattern()] self.regex =",
"class MockResolverDjango2None2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()]",
"'fake-view-name', False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected =",
"test_detect_access_is_by_role_with_roles(self): expected = u'Roles with access: role-1, role-2' view_access =",
"middleware.' def function(): pass view_access = Mock() view_access.type = 'pu'",
"self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected = u'View access is of",
"type By role.' expected += u'Roles with access: test1, test2'",
"self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected =",
"test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert",
"= [MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase):",
"def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected = u'Django roles access middleware",
"= u'fake-view-name' url = '/fake-url/' expected = u'\\n\\t\\tAnalysis for view:",
"'3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a1', 'b2',",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ):",
"self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none',",
"NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected =",
"for view: {}'.format(view_name) expected += u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url)",
"= 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access result =",
"= get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ):",
"expected = u'Roles with access: role-1, role-2' mock_view_access.type = 'br'",
"self.namespace = 'nested-namespace' class MockPatternDjango2: def __init__(self): self.pattern = '^fake-pattern/'",
"= None result = view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected = u'\\t' +",
"type='pu') result = view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected)",
"= MockRegexResolver() self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverNested:",
"mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c')] with self.assertRaises(TypeError):",
"view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.protected_view_by_role,",
"view_access result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def",
"resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback',",
"= [ # ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None # )",
"function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function())) def",
"mock_objects ): expected = u'No Django roles access tool used.",
"TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self):",
"= Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save()",
"{} type.'.format(app_name, app_type) expected += u'\\t\\t{} does not have configured",
"test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value",
"assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self):",
"is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns(",
"# def test_when_view_name_is_None(self): # expected_result = [ # ('fake-resolver/fake-pattern/', #",
"= ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is",
"'fake-app-name' self.namespace = 'nested-namespace' class MockPatternDjango2: def __init__(self): self.pattern =",
"analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected = u'' view_access =",
"): view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self,",
"u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header(",
"result = walk_site_url([resolver]) self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self): # expected_result",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result",
"def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text')",
"1) def test_cvs_format_write_correct_correct_middleware_status( self ): expected = u'Django roles access",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected = u'View access",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value",
"self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text')",
"patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style",
"'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver",
"u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result",
"result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result =",
"= u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row(",
"view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected = u'Django roles",
"'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects",
"type='br') result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t'",
"self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style) def tearDown(self):",
"= [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected,",
"def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result = ('direct_access_view/',",
"test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result,",
"result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/',",
"test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self ): expected = u'Django",
"test2' g1, created = Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access",
"in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"('a1', 'b2', 'c3', None)] expected_result = [('a', 'b', 'c')] result",
"+= u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def",
"= 'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self,",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1)",
"self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report')",
"'c', 'd', 'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self,",
"of walk_site_url and is required to return a dictionary with",
"expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' + SECURED_DEFAULT",
"= [MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjangoNested:",
"url = '/fake-url/' expected = u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected",
"result) def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result",
"'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a', 'b', 'c')]",
"View access object exist for the view, ' expected +=",
"fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self):",
"mock_settings.INSTALLED_APPS = ['fake-app-1'] result = get_views_by_app(self.data) assert 'fake-app-1' in result",
"assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self):",
"result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self):",
"expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result,",
"== 'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row)",
"expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected = u'View access",
"= Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access) self.assertEqual(result, expected)",
"'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result =",
"def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING:",
"'fake-namespace:fake-view-name', 'fake-app-name' )] resolver = MockResolver() result = walk_site_url([self.pattern_1, resolver])",
"template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self,",
"expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row)",
"self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report')",
"'b2', 'c3', None)] expected_result = [('a', 'b', 'c')] result =",
"u'\\t' + PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase):",
"def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text')",
"self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self",
"self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called def",
"def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view,",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ):",
"self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name',",
"access: role-1, role-2' view_access = ViewAccess.objects.create(view='any-name', type='br') role_1, created =",
"mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type = 'br' mock_objects.filter.return_value",
"result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/',",
"def test_without_middleware_with_view_access_object(self): expected = u'View access is of type By",
"expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} has no type.'.format(app_name)",
"= view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected(",
"1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value = 'fake-date'",
"= walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role,",
"'fake-app-3' not in result class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url =",
"def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self ): expected =",
"= walk_site_url([resolver]) self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self): # expected_result =",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects",
"'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected =",
"u'\\t' + NONE_TYPE_DEFAULT result = view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv'",
"fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report')",
"view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access(",
"result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used(",
"expected) def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' + NOT_SECURED_DEFAULT result =",
"access_by_role from django_roles_access.mixin import RolesMixin from django_roles_access.models import ViewAccess from",
"= Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"mock_view_access ): expected = u'' mock_view_access.type = 'pu' result =",
"self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected = u'ERROR:",
"self ): expected = u'ERROR: View access object exist for",
"= 'fake-app-name' self.namespace = 'nested-namespace' class MockPatternDjango2: def __init__(self): self.pattern",
"'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access =",
"view_access.type = 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access result",
"u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) expected",
"u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self",
"result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' +",
"tool used. Access to view depends ' expected += u'on",
"result of walk_site_url and is required to return a dictionary",
"test_report_for_application_type_DISABLED(self): expected = u'\\t' + DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result,",
"def test_detect_access_is_by_role(self): expected = u'ERROR: No roles configured to access",
"class MockRegexResolver: def __init__(self): self.pattern = '^fake-resolver/' class MockRegexResolverNested: def",
"= ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result)",
"import TemplateView try: from unittest.mock import Mock, patch, MagicMock except:",
"('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ]",
"): expected = u'ERROR: No roles configured to access de",
"import ViewAccess from tests import views from django_roles_access.utils import (walk_site_url,",
"test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report') def",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name(",
"self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format",
"from django.conf import settings from django.test import TestCase from django.views.generic",
"view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"= u'fake-app-name' app_type = None view_list = ['fake-view'] expected =",
"of type By role.' expected += u'ERROR: No roles configured",
"g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1)",
"import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT,",
"self._output._format == \\ 'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError) as e:",
"+= u'\\t\\t{} is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING:",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name',",
"= view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self):",
"expected = u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self):",
"= ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def",
"result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR:",
"def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake",
"view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected",
"= 'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name',",
"= u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"checking views access.\\n' expected += u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected)",
"no Django role access tool is used: neither ' expected",
"'^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-none' class MockResolverDjango2: def",
"self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type'",
"self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking view",
"roles configured to access de view.' view_access = ViewAccess.objects.create(view='any-name', type='br')",
"] resolver = MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result)",
"('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() nested_resolver",
"view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name",
"'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role,",
"text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def",
"setUp(self): self.pattern_1 = MockPattern() self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result",
"self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING:",
"= [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name'",
"+= u'ERROR: No roles configured to access de view.' ViewAccess.objects.create(",
"from django.test import TestCase from django.views.generic import TemplateView try: from",
"test_detect_view_is_decorated(self): @access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function():",
"self._output.write(u'some text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"django.test import TestCase from django.views.generic import TemplateView try: from unittest.mock",
"False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self ):",
"== \\ 'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError) as e: OutputReport()",
"result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/',",
"test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected = u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value",
"analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected =",
"assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ): view_access",
"'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app",
"fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING:",
"DISABLED_DEFAULT, OutputReport) class MockRegex: def __init__(self): self.pattern = '^fake-regex-pattern/$' class",
"self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjango2None: def __init__(self):",
"+= 'decorator, mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result =",
"result = walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive",
"dictionary with keys been installed applications. \"\"\" def setUp(self): self.data",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self):",
"'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected =",
"'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjangoNested: def __init__(self): self.pattern =",
"Public.' @access_by_role def function(): pass view_access = Mock() view_access.type =",
"= walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2",
"+= u'Roles with access: test1, test2' g1, created = Group.objects.get_or_create(name='test1')",
"active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self ):",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style(",
"type='pu') result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t'",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name',",
"result = get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected = u'\\t'",
"test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result =",
"= get_views_by_app(self.data) assert 'fake-app-1' in result assert 'fake-app-2' in result",
"mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result,",
"view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'SECURED',",
"from importlib import import_module from unittest import TestCase as UnitTestCase",
"u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self",
"MockPattern() self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result,",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False)",
"'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ):",
"and self._output._row == u'' assert hasattr(self._output, '_format') and self._output._format ==",
"self.callback = 'fake-callback' self.name = 'fake-view-none' class MockResolverDjango2: def __init__(self):",
"app_type, view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name =",
"test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result =",
"view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role')",
"import access_by_role from django_roles_access.mixin import RolesMixin from django_roles_access.models import ViewAccess",
"= get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings ):",
"expected = u'Roles with access: role-1, role-2' view_access = ViewAccess.objects.create(view='any-name',",
"expected) class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style",
"def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text')",
"expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected = u'ERROR: No",
"'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected",
"None result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def",
"test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected = u'Django roles access middleware is",
"'fake-view-none' class MockResolverDjango2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns =",
"MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result",
"MockResolver: def __init__(self): self.url_patterns = [MockPattern()] self.regex = MockRegexResolver() self.app_name",
"import Mock, patch from django_roles_access.decorator import access_by_role from django_roles_access.mixin import",
"expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self):",
"'^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace'",
"self.pattern = '^fake-nested-resolver/' class MockPattern: def __init__(self): self.regex = MockRegex()",
"gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self,",
"self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and self._output._row == u''",
"= 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected =",
"def test_report_for_application_type_PUBLIC(self): expected = u'\\t' + PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC')",
"self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result, list)",
"def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data =",
"'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access = Mock() view_access.type = 'pu'",
"access is of type By role.' expected += u'ERROR: No",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected = u'View",
"= u'fake-app-name' app_type = None view_list = ['fake-view-list'] expected =",
"views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase):",
"test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result =",
"UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(),",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, function, 'fake-view-name',",
"def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No roles configured to access",
"access is of type Public.' view_access = Mock() view_access.type =",
"= 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjangoNested: def __init__(self): self.pattern",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br')",
"view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected",
"expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None ) ] resolver",
"self, mock_objects ): expected = u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value =",
"def test_report_for_application_type_DISABLED(self): expected = u'\\t' + DISABLED_DEFAULT result = get_view_analyze_report('DISABLED')",
"+= u'\\t\\t{} is {} type.'.format(app_name, app_type) expected += u'\\t\\t{} does",
"self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access = Mock()",
"+= u'\\t\\t{} does not have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list)",
"): expected = u'View access is of type Public.' @access_by_role",
"'fake-app-2'] result = get_views_by_app(self.data) assert 'fake-app-1' in result assert 'fake-app-2'",
"u'\\t\\t{} does not have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name = u'fake-view-name' url =",
"mock_objects.first.return_value = None result = view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"self ): expected = u'Start checking views access.\\n' expected +=",
"= '/fake-url/' expected = u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected,",
"u'Django roles access middleware is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode)",
"self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def",
"'2', '3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a',",
"'fake-app-name' self.namespace = 'fake-namespace' class MockResolverNested: def __init__(self): self.url_patterns =",
"= u'fake-view-name' url = '/fake-url/' expected = u'{},{}'.format(view_name, url) self._output.set_format('csv')",
"mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active')",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c',",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected = u'\\n' self._output.set_format('csv') self._output.write_footer()",
"test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def",
"'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError) as e: OutputReport() def test_default_output_format_is_correct_type(self):",
"('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver = MockResolver() result =",
"IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result =",
"u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' )",
"None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [",
"self.namespace = 'fake-namespace' class MockResolverDjangoNested: def __init__(self): self.pattern = '^fake-nested-resolver/'",
"('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/',",
"u'fake-view-name' url = '/fake-url/' expected = u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name,",
"mock_objects.first.return_value = None result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access = Mock() view_access.type",
"test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback',",
"u'Start checking views access.\\n' expected += u'Start gathering information.' self._output.write_header()",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access",
"test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count,",
"a dictionary with keys been installed applications. \"\"\" def setUp(self):",
"] resolver = MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result, expected_result) #",
"Access to view depends ' expected += u'on its implementation.'",
"assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR:",
"'_row') and self._output._row == u'' assert hasattr(self._output, '_format') and self._output._format",
"'_format') and self._output._format == \\ 'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError)",
"result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected = u''",
"self ): expected = u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"[MockPatternDjango2None()] self.app_name = None self.namespace = None class MockResolverDjango2None2: def",
"class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style =",
"class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access ): expected = u'ERROR:",
"self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self, mock_view_access ): expected = u''",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected = u'View access",
"True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected =",
"view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"# 'fake-callback', 'fake-view-name', None # ) # ] # resolver",
"False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected =",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected = u'View",
"u'Django roles access middleware is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected",
"{}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name =",
"result = walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data)",
"def test_console_format_write_correct_end_of_header( self ): expected = u'Finish gathering information.' self._output.write_end_of_head()",
"pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html'",
"self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected",
"from unittest import TestCase as UnitTestCase from django.contrib.auth.models import Group",
"expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected = u'\\t' +",
"no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self):",
"u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self):",
"@patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access ): expected =",
"= [role_1, role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(",
"test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self):",
"app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name'",
"+= u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"get_views_by_app(self.data) assert 'fake-app-1' in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings",
"test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase):",
"+ NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"self, mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value =",
"= u'View access is of type Public.' view_access = Mock()",
"ViewAccess from tests import views from django_roles_access.utils import (walk_site_url, get_views_by_app,",
"view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{}",
"test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url)",
"self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name',",
"result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ):",
"view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type =",
"app_type = u'fake-app-type' view_list = [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv')",
"= MockResolver() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self):",
"is of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer(",
"type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer( 'SECURED', views.protected_view_by_role,",
"view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self):",
"def test_with_middleware_with_view_access_object_public(self): expected = u'View access is of type Public.'",
"self.mock_stdout assert self._output.style == self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row')",
"False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected =",
"= u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name, app_type)",
"nested_resolver = MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def",
"'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result =",
"'fake-callback', 'fake-view-name', None # ) # ] # resolver =",
"u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected += u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name,",
"self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected = u'ERROR: No",
"self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 = MockPattern()",
"MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback',",
"mock_objects ): view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value =",
"ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"= view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase):",
"= analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self, mock_view_access ): expected",
"u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"u'\\t\\t{} is {} type.'.format(app_name, app_type) expected += u'\\t\\t{} does not",
"u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def",
"= get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role,",
"): expected = u'' mock_view_access.type = 'pu' result = analyze_by_role(mock_view_access)",
"1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv'",
"def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text')",
"view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self, mock_objects",
"def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected = u'ERROR: View access",
"url) self.assertIn(expected, self._output._row) # View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text')",
"MockResolverDjango2None2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name",
"expected) def test_without_middleware_without_view_access_object_and_view_protected( self ): expected = u'\\t' + SECURED_DEFAULT",
"expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def",
"= view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self,",
"self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR:",
"django.contrib.auth.models import Group from django.core.management import BaseCommand from django.conf import",
"self._output.stdout == self.mock_stdout assert self._output.style == self.mock_style def test_internal_attributes_are_initialize(self): assert",
"views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout",
"def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list =",
"assert self._output.style == self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and",
"view_name = u'fake-view-name' url = '/fake-url/' expected = u'\\n\\t\\tAnalysis for",
"True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected =",
"'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result",
"test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected = u'Roles with access: role-1,",
"u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"assert self._output._format == 'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row)",
"result = view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type(",
"def test_default_output_format_is_correct_type(self): assert self._output._format == 'console' def test_set_format(self): self._output.set_format('csv') assert",
"test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected = u'Start checking views access.\\n' expected",
"= 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv'",
"result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected",
"): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style(",
"= None view_list = ['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv')",
"report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected =",
"u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End",
"= OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert",
"self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected",
"1) def test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected)",
"import Mock, patch, MagicMock except: from mock import Mock, patch",
"import RolesMixin from django_roles_access.models import ViewAccess from tests import views",
"= 'fake-namespace' class MockResolverNested: def __init__(self): self.url_patterns = [MockResolver()] self.regex",
"'fake-view-name', 'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access",
"'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects",
"self.namespace = 'fake-namespace' class MockResolverNested: def __init__(self): self.url_patterns = [MockResolver()]",
"class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result",
"view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called def",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self,",
"= u'ERROR: No roles configured to access de view.' mock_view_access.type",
"test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected = u'View access is of",
"mock import Mock, patch from django_roles_access.decorator import access_by_role from django_roles_access.mixin",
"DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected =",
"expected = u'View access is of type Public.' view_access =",
"self._output.style == self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and self._output._row",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def",
"def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text')",
"view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"): expected = u'Start checking views access.\\n' expected += u'Start",
"text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self):",
"self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class MockPatternDjango2: def __init__(self):",
"list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS",
"UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access ): expected = u'ERROR: No",
"'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result =",
"'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() nested_resolver =",
"try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects",
"type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"test_report_for_application_type_SECURED(self): expected = u'\\t' + SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result,",
"test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url)",
"= get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ):",
"def test_initial_without_parameter(self): with self.assertRaises(TypeError) as e: OutputReport() def test_default_output_format_is_correct_type(self): assert",
"'^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace = 'nested-namespace'",
"assert 'fake-app-1' in result assert 'fake-app-2' in result @patch('django_roles_access.utils.settings') def",
"def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access'])",
"expected) def test_with_middleware_with_view_access_object_public(self): expected = u'View access is of type",
"g1, created = Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access =",
"= mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', function, 'fake-view-name',",
"= view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self):",
"= view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self):",
"self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects ):",
"'^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name = None self.namespace = None",
"'^fake-regex-pattern/$' class MockRegexResolver: def __init__(self): self.pattern = '^fake-resolver/' class MockRegexResolverNested:",
"expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected = u'\\t' +",
"self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected = u'\\tFinish analyzing",
"analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex:",
"in result class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def",
"@patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data",
"self, mock_objects ): expected = u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value =",
"[ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name'",
") ] result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self):",
"= [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result, list) def",
"for the view, but no ' expected += u'Django role",
"1) def test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url = '/fake-url/' expected",
"ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected",
"patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output =",
"+= u'on its implementation.' def function(): pass mock_objects.filter.return_value = mock_objects",
"= ['fake-view-list'] expected = u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type,",
"def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type",
"): view_name = u'fake-view-name' url = '/fake-url/' expected = u'\\n\\t\\tAnalysis",
"self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ):",
"mock_timezone ): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count,",
"self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report')",
"u'ERROR: No roles configured to access de view.' view_access =",
"def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n'",
"MockResolverDjango2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name",
"None result = view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result, expected) class",
"= 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects",
"u'fake-app-name' app_type = u'fake-app-type' view_list = [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name)",
"self.url_patterns = [MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class",
"self ): expected = u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name, app_type,",
"@patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2']",
"expected) def test_detect_access_is_not_by_role(self): expected = u'' view_access = ViewAccess.objects.create(view='any-name', type='pu')",
"view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def",
"result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/',",
"def test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role')",
"test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/',",
"is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer(",
"expected_result) def test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None",
"expected += u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format",
"= 'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback',",
"u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback',",
"result) def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name')",
"test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name = u'fake-view-name' url = '/fake-url/'",
"test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result,",
"u'View access is of type By role.' expected += u'ERROR:",
"MockResolverNested() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result",
"= ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def",
"self.name = 'fake-view-name' class MockPatternDjango2None: def __init__(self): self.pattern = '^fake-pattern/'",
"self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback',",
"[ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )]",
"'fake-view-name' class MockPatternDjango2None: def __init__(self): self.pattern = '^fake-pattern/' self.callback =",
"view, but no ' expected += u'Django role access tool",
"resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback',",
"self ): expected = u'Django roles access middleware is active:",
"'^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-name' class MockPatternDjango2None: def",
"'\\t\\t' + 'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format =",
"get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected = u'\\t'",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('NOT_SECURED', 'fake-callback',",
"text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"def test_cvs_format_write_correct_correct_middleware_status( self ): expected = u'Django roles access middleware",
"self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) # View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self):",
"role-1, role-2' mock_view_access.type = 'br' role_1 = Mock() role_1.name =",
"view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected",
"def __init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name =",
"u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected",
"= walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result,",
"= view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self,",
"self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some",
"self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjangoNested: def __init__(self):",
"SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result)",
"): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"View access object exist for the view, but no '",
"def test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result =",
"self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value =",
"PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC',",
"NONE_TYPE_DEFAULT result = view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"and self._output._format == \\ 'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError) as",
"self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess')",
"'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self):",
"# resolver = MockResolverDjango2None2() # result = walk_site_url([resolver]) # print(result)",
"result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected = u'\\t'",
"= view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result,",
"from django_roles_access.models import ViewAccess from tests import views from django_roles_access.utils",
"self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class",
"MockRegex() self.callback = 'fake-callback' self.name = 'fake-view-name' class MockResolver: def",
"unittest import TestCase as UnitTestCase from django.contrib.auth.models import Group from",
"get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings",
"walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_'",
"No roles configured to access de view.' mock_view_access.type = 'br'",
"= ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result = walk_site_url(self.url) self.assertIn(expected_result, result)",
"configured to access de view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value =",
"= u'\\t' + DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def",
"= 'fake-view-name' class MockResolver: def __init__(self): self.url_patterns = [MockPattern()] self.regex",
"mock_view_access.type = 'br' mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result,",
"True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected = u'View access is",
"view_access.save() result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected)",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ):",
"result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result",
"configured to access de view.' view_access = ViewAccess.objects.create(view='any-name', type='br') result",
"SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('SECURED',",
"{}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) expected +=",
"get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1']",
"'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected =",
"access middleware is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected = u'View",
"self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected = u'\\t' + PUBLIC_DEFAULT result",
"= 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ):",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ):",
"of type By role.' expected += u'Roles with access: test1,",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result,",
"Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"with access: test1, test2' g1, created = Group.objects.get_or_create(name='test1') g2, created",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected = u'\\n' self._output.set_format('csv') self._output.write_footer() self.assertEqual(self._output._row,",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected = u'View access",
"test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback',",
"from django.views.generic import TemplateView try: from unittest.mock import Mock, patch,",
"expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name,",
"u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected",
"= get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def",
"= 'br' role_1 = Mock() role_1.name = u'role-1' role_2 =",
"self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name',",
"'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern =",
"u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view'] expected = u'\\tAnalyzing:",
"= u'ERROR: View access object exist for the view, '",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count,",
"is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/',",
"u'Roles with access: role-1, role-2' mock_view_access.type = 'br' role_1 =",
"'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self):",
"view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected",
"result = view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED(",
"] result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result",
"def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list =",
"self._output.set_format('csv') assert self._output._format == 'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text',",
"def test_cvs_format_write_correct_csv_columns( self ): expected = u'App Name,Type,View Name,Url,Status,Status description'",
"u'on its implementation.' def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects",
"installed applications. \"\"\" def setUp(self): self.data = [('a', 'b', 'c',",
"result = get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings",
"u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self",
"= u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view-list'] expected =",
"None self.namespace = None class MockResolverDjango2None2: def __init__(self): self.pattern =",
"resolver = MockResolver() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def",
"MagicMock except: from mock import Mock, patch from django_roles_access.decorator import",
"= ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class",
"self._output.write(u'some text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text')",
"None result = view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result, expected) def",
"self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report')",
"('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver",
"False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(),",
"def test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None]",
"access: test1, test2' g1, created = Group.objects.get_or_create(name='test1') g2, created =",
"test_without_middleware_without_view_access_object_and_view_protected( self ): expected = u'\\t' + SECURED_DEFAULT result =",
"test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected = u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value",
"'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv'",
"PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self):",
"view_access = ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects')",
"True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected =",
"= Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save()",
"expected) def test_without_middleware_with_view_access_object(self): expected = u'View access is of type",
"): expected = u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected)",
"view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected",
"None view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected +=",
"@patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data",
"role_1 = Mock() role_1.name = u'role-1' role_2 = Mock() role_2.name",
"mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False)",
"test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some",
"= '^fake-nested-resolver/' class MockPattern: def __init__(self): self.regex = MockRegex() self.callback",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ):",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url))",
"= analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected",
"= Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role',",
"def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access = Mock() view_access.type =",
"result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings",
"expected = u'\\t' + PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected)",
"roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result",
"== u'' assert hasattr(self._output, '_format') and self._output._format == \\ 'console'",
"mock_objects.first.return_value = None result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"view_access.save() result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self):",
"= get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected =",
"view_access = ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access) self.assertEqual(result, expected) def",
"object exist for the view, but no ' expected +=",
"= '^fake-regex-pattern/$' class MockRegexResolver: def __init__(self): self.pattern = '^fake-resolver/' class",
"def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected = u'Start checking views access.\\n'",
"result = get_views_by_app(self.data) assert 'fake-app-1' in result assert 'fake-app-2' in",
"'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access =",
"def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected = u'\\t' + NONE_TYPE_DEFAULT result",
"test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = []",
"view_access.type = 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type',",
"'b', 'c')] result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name(",
"= view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self):",
"self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view',",
"'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result",
"class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the result of walk_site_url and",
"= view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT)",
"active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self",
"TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected = u'\\t' + NONE_TYPE_DEFAULT result =",
"test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result = walk_site_url(self.url) self.assertIn(expected_result,",
"views from django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role,",
"its implementation.' def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view,",
"+ SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"By role.' expected += u'ERROR: No roles configured to access",
"expected += u'Roles with access: test1, test2' g1, created =",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self ): expected = u'Django roles",
"= ['fake-app-1'] data = [('a', 'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data)",
"= analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected = u'Roles with",
"self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self):",
"role-1, role-2' view_access = ViewAccess.objects.create(view='any-name', type='br') role_1, created = Group.objects.get_or_create(name='role-1')",
"test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] result = get_views_by_app(self.data)",
"from unittest.mock import Mock, patch, MagicMock except: from mock import",
"'console' def test_set_format(self): self._output.set_format('csv') assert self._output._format == 'csv' def test_add_to_row(self):",
"'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result =",
"= analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected",
"): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data = [('a', 'b',",
"('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() result",
"self._output._row) # View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True)",
"self, mock_view_access ): expected = u'Roles with access: role-1, role-2'",
"result = get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t'",
"in result assert 'fake-app-2' in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self,",
"expected = u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"Mock, patch from django_roles_access.decorator import access_by_role from django_roles_access.mixin import RolesMixin",
"def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/',",
"= view_access result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected)",
"'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview))",
"result = walk_site_url([resolver]) # print(result) # self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase):",
"exist for the view, but no ' expected += u'Django",
"['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected,",
"None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2()",
"'nested-namespace' class MockPatternDjango2: def __init__(self): self.pattern = '^fake-pattern/' self.callback =",
"def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name =",
"mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase):",
"= ['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list)",
"# self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns",
"1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access = Mock() view_access.type",
"test_console_format_write_correct_end_of_header( self ): expected = u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected)",
"assert self._output.stdout == self.mock_stdout assert self._output.style == self.mock_style def test_internal_attributes_are_initialize(self):",
"roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result",
"type.'.format(app_name, app_type) expected += u'\\t\\t{} does not have configured views.'.format(app_name)",
"= u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"access tool is used: neither decorator, ' expected += u'mixin,",
"TestCase from django.views.generic import TemplateView try: from unittest.mock import Mock,",
"self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake report') def",
"u'fake-app-name' app_type = u'fake-app-type' view_list = [] expected = u'\\tAnalyzing:",
"def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class",
"get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT,",
"expected) def test_report_for_application_type_PUBLIC(self): expected = u'\\t' + PUBLIC_DEFAULT result =",
"importlib import import_module from unittest import TestCase as UnitTestCase from",
"expected = u'ERROR: View access object exist for the view,",
"def __init__(self): self.url_patterns = [MockPattern()] self.regex = MockRegexResolver() self.app_name =",
"fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format",
"list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1']",
"['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} has no",
"expected) def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type",
"None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback",
"role access tool is used: neither ' expected += 'decorator,",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected = u'View access",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, function,",
"): expected = u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer( None, views.middleware_view,",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type = u'fake-app-type'",
"Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"exist for the view, ' expected += 'but no Django",
"self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected = u'\\t'",
"ViewAccess.objects.create(view='any-name', type='br') role_1, created = Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2')",
"roles access middleware is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"def test_detect_access_is_not_by_role( self, mock_view_access ): expected = u'' mock_view_access.type =",
"self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count,",
"expected += u'on its implementation.' def function(): pass mock_objects.filter.return_value =",
"test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected = u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value",
"walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/',",
"mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data = [('a', 'b', 'c',",
"self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result",
"def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self):",
"= u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view'] expected =",
"has no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"from django_roles_access.decorator import access_by_role from django_roles_access.mixin import RolesMixin from django_roles_access.models",
"mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer( None,",
"is {} type.'.format(app_name, app_type) expected += u'\\t\\t{} does not have",
"PUBLIC_DEFAULT @access_by_role def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None # ) # ] #",
"u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result, expected)",
"settings from django.test import TestCase from django.views.generic import TemplateView try:",
"= u'Django roles access middleware is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False)",
"None] data = [('a', 'b', 'c', 'fake-app-1'), ('1', '2', '3',",
"except: from mock import Mock, patch from django_roles_access.decorator import access_by_role",
"'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report')",
"= ['fake-app-1', 'fake-app-2', None] result = get_views_by_app(self.data) assert 'fake-app-3' not",
"of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer( 'SECURED',",
"resolver = MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result, expected_result) # def",
"u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result",
"test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected)",
"de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view,",
"assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style(",
"= analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self,",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] result = get_views_by_app(self.data)",
"type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view,",
"@access_by_role def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"Public.' view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects",
"('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def",
"None] result = get_views_by_app(self.data) assert 'fake-app-3' not in result class",
"mock_objects ): expected = u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects",
"): expected = u'\\t' + PUBLIC_DEFAULT @access_by_role def function(): pass",
"self.regex = MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class",
"u'fake-app-name' app_type = None view_list = ['fake-view'] expected = u'\\tAnalyzing:",
"True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected =",
"('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class",
"('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result, result)",
"= import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None)",
"+= u'Django role access tool is used: neither decorator, '",
"1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some",
"import TestCase from django.views.generic import TemplateView try: from unittest.mock import",
"self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout ==",
"views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) assert",
"pattern_2.callback = 'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback',",
"[MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjangoNested: def",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True)",
"app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type",
"+ 'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert",
"self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected = u'\\t' + DISABLED_DEFAULT result",
"'fake-app-name' ) ] resolver = MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True)",
"get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS",
"url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name",
"[role_1, role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self,",
"APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex: def",
"[ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name'",
"def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR:",
"= walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2',",
"created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2)",
"): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b', 'c')] with",
"expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name',",
"type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view,",
"): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list)",
"Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2] result =",
"mock_objects.first.return_value = None result = view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result,",
"= None result = view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result, expected)",
"text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def",
"'b2', 'c3', None)] expected_result = [('a1', 'b2', 'c3')] result =",
"# View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def",
") # ] # resolver = MockResolverDjango2None2() # result =",
"u'fake-app-type' view_list = [] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected +=",
"def test_detect_access_is_by_role_with_roles(self): expected = u'Roles with access: role-1, role-2' view_access",
"result = get_views_by_app(self.data) assert 'fake-app-3' not in result class IntegratedTestGetViewsByApp(TestCase):",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', function, 'fake-view-name', False)",
"role_1.name = u'role-1' role_2 = Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value",
"self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected = u'' view_access = ViewAccess.objects.create(view='any-name',",
"False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self, mock_objects ): expected =",
"'but no Django role access tool is used: neither '",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self ): expected = u'Finish gathering",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type'",
"is of type By role.' expected += u'Roles with access:",
"[ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )",
"test_report_for_application_type_PUBLIC(self): expected = u'\\t' + PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result,",
"of type Public.' view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value",
"u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"test_with_middleware_with_view_access_object(self): expected = u'View access is of type By role.'",
"pass view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects",
"or middleware.' def function(): pass view_access = Mock() view_access.type =",
"u'' view_access = ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access) self.assertEqual(result, expected)",
"'3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a', 'b',",
"'fake-callback' self.name = 'fake-view-name' class MockPatternDjango2None: def __init__(self): self.pattern =",
"mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try:",
"def test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin,",
"self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def function(): pass",
"mock_view_access.type = 'br' role_1 = Mock() role_1.name = u'role-1' role_2",
"self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self): # expected_result = [ #",
"= MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self):",
"function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self, mock_objects ):",
"\\ 'console' def test_initial_without_parameter(self): with self.assertRaises(TypeError) as e: OutputReport() def",
"+= 'but no Django role access tool is used: neither",
"self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a', 'b',",
"= view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self,",
"['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) assert 'fake-app-1' in result assert",
"data = [('a', 'b', 'c', 'd', 'e')] with self.assertRaises(TypeError): get_views_by_app(data)",
"= [('a1', 'b2', 'c3')] result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings')",
"access is of type Public.' @access_by_role def function(): pass view_access",
"type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result,",
"'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected =",
"expected) def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert",
"access tool used. Access to view depends ' expected +=",
"True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access is",
"@access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function(): pass",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name')",
"1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ): view_access =",
"self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No roles configured",
"test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected = u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected)",
"= '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name = None self.namespace =",
"'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver",
"view, ' expected += 'but no Django role access tool",
"text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected = u'Start",
"resolver = MockResolverNested() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def",
"tool is used: neither decorator, ' expected += u'mixin, or",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def",
"access.\\n' expected += u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self, mock_view_access ):",
"fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called def",
"test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and self._output._row == u'' assert hasattr(self._output,",
"def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result",
"u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result",
"view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name = u'fake-view-name'",
"walk_site_url([resolver]) # print(result) # self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self):",
"walk_site_url and is required to return a dictionary with keys",
"patch from django_roles_access.decorator import access_by_role from django_roles_access.mixin import RolesMixin from",
"self.regex = MockRegexResolver() self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class",
"'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def",
"expected = u'\\t' + NONE_TYPE_DEFAULT result = view_access_analyzer( None, views.protected_view_by_role,",
"to access de view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value = 0",
"view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects",
"Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result =",
"= view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self,",
"= ['fake-app-1'] result = get_views_by_app(self.data) assert 'fake-app-1' in result @patch('django_roles_access.utils.settings')",
"= u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected =",
"access is of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result =",
"result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/',",
"['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings')",
"view.' view_access = ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected)",
"= u'\\t' + NONE_TYPE_DEFAULT result = view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None),",
"= view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self):",
"+ PUBLIC_DEFAULT @access_by_role def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected = u'View access is of type",
"self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv')",
"= view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT)",
"def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ),",
"self.pattern = '^fake-regex-pattern/$' class MockRegexResolver: def __init__(self): self.pattern = '^fake-resolver/'",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('SECURED', 'fake-callback',",
"def test_with_middleware_with_view_access_object(self): expected = u'View access is of type By",
"class MockResolverDjango2None: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()]",
"view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects",
"not have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result =",
"expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name'",
"['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {}",
"= [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name'",
"function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects ):",
"= 'fake-view-none' class MockResolverDjango2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns",
"= walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the",
"MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result = walk_site_url([self.pattern_1,",
"1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list",
"class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 = MockPattern() self.data = [self.pattern_1]",
"checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected",
"= MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class MockPatternDjango2:",
"tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout assert",
"self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverNested: def __init__(self):",
"'fake-callback', 'fake-view-none', None ) ] resolver = MockResolverDjango2None2() result =",
"except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access =",
"= analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected = u'' view_access",
"= u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style(",
"report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"TemplateView try: from unittest.mock import Mock, patch, MagicMock except: from",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected = u'View access",
"= None self.namespace = None class MockResolverDjango2None2: def __init__(self): self.pattern",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type = None",
"self, mock_view_access ): expected = u'' mock_view_access.type = 'pu' result",
"url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) # View_access_analyzer output. def",
"self.url_patterns = [MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class",
"= u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu')",
"def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected = u'ERROR: No roles",
"views access.\\n' expected += u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result =",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def",
"): expected = u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result =",
"'fake-site-active') try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self,",
"Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result",
"def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected = u'\\t' + NOT_SECURED_DEFAULT",
"expected = u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) #",
"test_initial_without_parameter(self): with self.assertRaises(TypeError) as e: OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format",
"'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ):",
"type='br') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected)",
"expected) def test_without_middleware_with_view_access_object_authorized(self): expected = u'View access is of type",
"u'mixin, or middleware.' def function(): pass view_access = Mock() view_access.type",
"= u'role-1' role_2 = Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value =",
"depends ' expected += u'on its implementation.' def function(): pass",
"try: from unittest.mock import Mock, patch, MagicMock except: from mock",
"middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func',",
"view_access = Mock() view_access.type = 'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"u'\\t\\t{} is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"expected += u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"mock_objects ): expected = u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value = mock_objects",
"view_name = u'fake-view-name' url = '/fake-url/' expected = u'{},{}'.format(view_name, url)",
"data = [('a', 'b', 'c', 'fake-app-1'), ('1', '2', '3', 'fake-app-2'),",
"False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_authorized(self): expected = u'View access is",
"to access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer(",
"access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result =",
"self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self):",
"access is of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result =",
"'fake-app-1'), ('1', '2', '3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result",
"IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result =",
"view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"__init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name = None",
"self ): expected = u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head()",
"True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu')",
"class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' + SECURED_DEFAULT result",
"report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self):",
"expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.protected_view_by_role,",
"created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2)",
"= ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def",
"text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type =",
"resolver = MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver])",
"@patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ): view_access = Mock()",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type =",
"def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name =",
"= u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row)",
"self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self ): expected =",
"is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self",
") ] resolver = MockResolverNested() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result,",
"'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverNested() result =",
"'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def",
"'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role,",
"expected = u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role',",
"in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"type='au') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"= None result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"): expected = u'No Django roles access tool used. Access",
"self.app_name = None self.namespace = None class MockResolverDjango2None2: def __init__(self):",
"pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('Authorized',",
"to access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer(",
"No roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br')",
"expected) def test_no_django_roles_tools_used_application_type( self, mock_objects ): expected = u'No Django",
"= MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result =",
"def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout')",
"[self.pattern_1] def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self):",
"self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self):",
"get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' + NOT_SECURED_DEFAULT",
"result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def",
"= 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def",
"result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'NOT_SECURED',",
"mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"= 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header(",
"assert hasattr(self._output, '_format') and self._output._format == \\ 'console' def test_initial_without_parameter(self):",
"hasattr(self._output, '_row') and self._output._row == u'' assert hasattr(self._output, '_format') and",
"= [MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjango2None:",
"middleware is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header(",
"test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result =",
"self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role')",
"type Public.' view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value =",
"= u'End checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"self._output._format == 'console' def test_set_format(self): self._output.set_format('csv') assert self._output._format == 'csv'",
"result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result =",
"assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access = Mock()",
"test_when_view_name_is_None(self): # expected_result = [ # ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name',",
"@patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2',",
"result = view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type(",
"result class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self):",
"expected) def test_report_for_application_type_SECURED(self): expected = u'\\t' + SECURED_DEFAULT result =",
"type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def",
"= ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer(",
"ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"= get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role,",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, function, 'fake-view-name', False)",
"\"\"\" def setUp(self): self.data = [('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings')",
"test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] data = [('a',",
"pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2])",
"view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
") ] resolver = MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result,",
"True) self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ):",
"function, 'fake-view-name', False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected",
"'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected =",
"def test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected = u'No Django roles",
"self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self ): expected",
"+ SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected,",
"self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ): view_access",
"role_1, created = Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2)",
"resolver = MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def",
"self.regex = MockRegex() self.callback = 'fake-callback' self.name = 'fake-view-name' class",
"import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result =",
"self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role',",
"view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result =",
"'fake-app-2', None] result = get_views_by_app(self.data) assert 'fake-app-3' not in result",
"self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access is of",
"): expected = u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"from mock import Mock, patch from django_roles_access.decorator import access_by_role from",
"'fake-app-name' )] resolver = MockResolver() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result,",
"u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected = u'\\tFinish analyzing fake-app-name.'",
"[] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row)",
"'/fake-url/' expected = u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row)",
"'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self ):",
"expected) def test_detect_access_is_by_role_with_roles(self): expected = u'Roles with access: role-1, role-2'",
"'fake-view-name', None # ) # ] # resolver = MockResolverDjango2None2()",
"= u'No Django roles access tool used. Access to view",
"mock_view_access.type = 'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles(",
"= patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output",
"'fake-namespace' class MockResolverDjango2None: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns =",
"None result = view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result, expected) def",
"('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def",
"self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format",
"def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer(",
"pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self):",
"pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None,",
"mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result,",
"= ['fake-app-1', 'fake-app-2', None] data = [('a', 'b', 'c', 'fake-app-1'),",
"None result = view_access_analyzer('PUBLIC', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def",
"def __init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name =",
"self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected = u'View access is of",
"def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/',",
") ] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self):",
"self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style')",
"self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the result of",
"setUp(self): self.patch_mock_stdout = patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout",
"__init__(self): self.regex = MockRegex() self.callback = 'fake-callback' self.name = 'fake-view-name'",
"__init__(self): self.pattern = '^fake-nested-resolver/' class MockPattern: def __init__(self): self.regex =",
"get_views_by_app receive the result of walk_site_url and is required to",
"== 'console' def test_set_format(self): self._output.set_format('csv') assert self._output._format == 'csv' def",
"= view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self,",
"pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)])",
"expected += 'decorator, mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu') result",
"= None result = view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result, expected)",
"u'ERROR: View access object exist for the view, ' expected",
"mock_view_access ): expected = u'Roles with access: role-1, role-2' mock_view_access.type",
"def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected)",
"# result = walk_site_url([resolver]) # print(result) # self.assertEqual(result, expected_result) class",
"is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer(",
"'fake-view-none', None ) ] resolver = MockResolverDjango2None2() result = walk_site_url([resolver])",
"test_detect_access_is_by_role( self, mock_view_access ): expected = u'ERROR: No roles configured",
"def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR:",
"def __init__(self): self.url_patterns = [MockResolver()] self.regex = MockRegexResolverNested() self.app_name =",
"middleware is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url))",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('DISABLED', 'fake-callback',",
"self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n'",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View",
"view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type(",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self):",
"self.mock_style = self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop()",
"self.assertRaises(TypeError) as e: OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format == 'console'",
"= Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\",
"'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) # View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some",
"class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected = u'\\t' + NONE_TYPE_DEFAULT result",
"result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED(",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access)",
"Mock, patch, MagicMock except: from mock import Mock, patch from",
"fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count,",
"expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected = u'\\t' +",
"the result of walk_site_url and is required to return a",
"test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count,",
"'fake-view-name', True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects",
"SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex: def __init__(self): self.pattern",
"[('a', 'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self,",
"'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result = [('a1', 'b2', 'c3')]",
"role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access)",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"# expected_result = [ # ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None",
"view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected",
"= ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name'])",
"= [('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings",
"def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/',",
"= walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [",
"result) def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called",
"def test_when_view_name_is_None(self): # expected_result = [ # ('fake-resolver/fake-pattern/', # 'fake-callback',",
"hasattr(self._output, '_format') and self._output._format == \\ 'console' def test_initial_without_parameter(self): with",
"view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create(",
"[ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' )",
"mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'],",
"No roles configured to access de view.' view_access = ViewAccess.objects.create(view='any-name',",
"self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected =",
"By role.' expected += u'Roles with access: test1, test2' g1,",
"): mock_settings.INSTALLED_APPS = ['fake-app-1'] result = get_views_by_app(self.data) assert 'fake-app-1' in",
"'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected",
"= walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result = [",
"neither decorator, ' expected += u'mixin, or middleware.' def function():",
"keys been installed applications. \"\"\" def setUp(self): self.data = [('a',",
"expected_result) # def test_when_view_name_is_None(self): # expected_result = [ # ('fake-resolver/fake-pattern/',",
"= u'fake-app-type' view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected",
"self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self ): expected = u'Start checking",
"is of type By role.' expected += u'ERROR: No roles",
"= mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name',",
"self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking view access.'",
"expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self):",
"view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT,",
"None result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def",
"description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name =",
"['fake-app-1'] data = [('a', 'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings')",
"expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None),",
"mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected = u'View access",
"u'\\t' + PUBLIC_DEFAULT @access_by_role def function(): pass mock_objects.filter.return_value = mock_objects",
"self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected = u'No",
"self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format =",
"None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None),",
"def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access = Mock() view_access.type =",
"(walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT, SECURED_DEFAULT, PUBLIC_DEFAULT,",
"role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access",
"view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type =",
"__init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name = 'fake-app-name'",
"self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some",
"view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self): #",
"None)] expected_result = [('a', 'b', 'c')] result = get_views_by_app(data) self.assertEqual(expected_result,",
"tool is used: neither ' expected += 'decorator, mixin, or",
"self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name =",
"'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str) def",
"self.url_patterns = [MockResolver()] self.regex = MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace",
"def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/',",
"ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected",
"expected) def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No roles configured to",
"= 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback',",
"RolesMixin from django_roles_access.models import ViewAccess from tests import views from",
"expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE])",
"u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected = u'View access is",
"= 'fake-namespace' class MockResolverDjango2None: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns",
"'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/',",
"= view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self,",
"self, mock_objects ): expected = u'View access is of type",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout,",
"): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) assert 'fake-app-1'",
"view_list = ['fake-view-list'] expected = u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name,",
"Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br')",
"fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected =",
"BaseCommand from django.conf import settings from django.test import TestCase from",
"def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)])",
"None) result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result =",
"def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected = u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name')",
"test_cvs_format_write_correct_csv_columns( self ): expected = u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv')",
"class MockResolverNested: def __init__(self): self.url_patterns = [MockResolver()] self.regex = MockRegexResolverNested()",
"+ DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name =",
"def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list =",
"def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def",
"= ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list)",
"self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name',",
"unicode) except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access",
"= import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result",
"fake report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with(",
"u'role-1' role_2 = Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value = [role_1,",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type =",
"expected = u'Start checking views access.\\n' expected += u'Start gathering",
"class MockPatternDjango2: def __init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback'",
"self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format =",
"import views from django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used,",
"= view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self,",
"+ 'WARNING: fake report') def test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv'",
"view='django_roles_access:middleware_view_func', type='pu') result = view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result,",
"= 'fake-namespace' class MockResolverDjangoNested: def __init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns",
"= '^fake-resolver/' class MockRegexResolverNested: def __init__(self): self.pattern = '^fake-nested-resolver/' class",
"self.assertEqual(mock_analyze_by_role.call_count, 1) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ): view_access",
"'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access",
"def test_without_middleware_without_view_access_object_and_view_protected( self ): expected = u'\\t' + SECURED_DEFAULT result",
"= u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def",
"self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name',",
"expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected = u'ERROR: View access",
"= view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self):",
"result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback',",
"django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE, NOT_SECURED_DEFAULT,",
"with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS",
"test_report_for_no_application_type(self): expected = u'\\t' + NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result,",
"self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name =",
"test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name = u'fake-view-name' url = '/fake-url/' expected",
"= u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected += u'\\n\\t\\tView url: {}'.format(url)",
"= [('a', 'b', 'c', 'fake-app-1'), ('1', '2', '3', 'fake-app-2'), ('a1',",
"class Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class",
"= walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [",
"app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name",
"'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjango2None: def __init__(self): self.pattern =",
"def test_set_format(self): self._output.set_format('csv') assert self._output._format == 'csv' def test_add_to_row(self): self._output.add_to_row('text')",
"self.pattern_1 = MockPattern() self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result =",
"= u'\\t' + NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result, expected) def",
"def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected = u'Roles with access:",
"view_access.type = 'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type',",
"): expected = u'ERROR: View access object exist for the",
"text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called",
"): expected = u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"None # ) # ] # resolver = MockResolverDjango2None2() #",
"'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name',",
"TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name",
"DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('DISABLED',",
"expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result = walk_site_url(self.url)",
"= Mock() view_access.type = 'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"__init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name = 'fake-app-name'",
"def test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] result =",
"'fake-callback' self.name = 'fake-view-none' class MockResolverDjango2: def __init__(self): self.pattern =",
"+ NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects",
"= '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace =",
"test_view_analyzer_return_a_report( self, mock_objects ): view_access = Mock() view_access.type = 'pu'",
"mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(",
"[('a', 'b', 'c')] result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def",
"expected += u'Django role access tool is used: neither decorator,",
"ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type = None",
"'fake-namespace' class MockResolverDjangoNested: def __init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns =",
"test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url = '/fake-url/' expected = u'{},{}'.format(view_name,",
"test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view-list']",
"self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text')",
"'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver = MockResolver() result = walk_site_url([self.pattern_1,",
"= None result = view_access_analyzer(None, function, 'fake-view-name', False) self.assertEqual(result, expected)",
"MockResolverNested: def __init__(self): self.url_patterns = [MockResolver()] self.regex = MockRegexResolverNested() self.app_name",
"expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list)",
"self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected = u'\\t'",
"neither ' expected += 'decorator, mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func',",
"'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self):",
"def function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function()))",
"['fake-app-1'] result = get_views_by_app(self.data) assert 'fake-app-1' in result @patch('django_roles_access.utils.settings') def",
"None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def setUp(self):",
")] resolver = MockResolver() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result)",
"expected_result = [('a1', 'b2', 'c3')] result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE])",
"MockResolver() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects",
"): expected = u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"None ) ] resolver = MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result,",
"view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self",
"= Mock() role_1.name = u'role-1' role_2 = Mock() role_2.name =",
"result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected",
"'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result",
"= u'Django roles access middleware is active: False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None ) ]",
"expected) def test_detect_access_is_not_by_role( self, mock_view_access ): expected = u'' mock_view_access.type",
"= u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS())",
"view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type",
"result = view_access_analyzer('Authorized', function, 'fake-view-name', False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase):",
"__init__(self): self.pattern = '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name = 'fake-app-name'",
"expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access'])",
"MockPatternDjango2None: def __init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name",
"gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status( self ):",
"__init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-name'",
"walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/',",
"test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback',",
"test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = []",
"test_csv_format_write_view_access_analyzer_with_WARNING_with_style( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True)",
"access de view.' view_access = ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access)",
"mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects",
"MockRegexResolver() self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverNested: def",
"= 'fake-callback' self.name = 'fake-view-name' class MockResolver: def __init__(self): self.url_patterns",
"'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self, mock_objects ): expected",
"('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()])",
"'fake-app-name' self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 =",
"Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name",
"\"\"\" get_views_by_app receive the result of walk_site_url and is required",
"Mock() view_access.type = 'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access",
"view_access_analyzer('PUBLIC', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects",
"= 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 = MockPattern() self.data",
"None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ):",
"assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self):",
"role_2 = Mock() role_2.name = u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2]",
"def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self):",
"u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url) self.assertIn(expected, self._output._row) # View_access_analyzer output.",
"self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text') def test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert",
"with keys been installed applications. \"\"\" def setUp(self): self.data =",
"= self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop()",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View",
"def test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url = '/fake-url/' expected =",
"def function(): pass view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value",
"test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected = u'ERROR: No roles configured",
"view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self",
"self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some",
"class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function)) def",
"expected = u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role',",
"= u'fake-app-type' view_list = [] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected",
"@patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2',",
"test_set_format(self): self._output.set_format('csv') assert self._output._format == 'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other')",
"'b', 'c', 'fake-app-1'), ('1', '2', '3', 'fake-app-2'), ('a1', 'b2', 'c3',",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name',",
"test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-pattern/', 'fake-callback',",
"] # resolver = MockResolverDjango2None2() # result = walk_site_url([resolver]) #",
"'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self,",
"[MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def",
"+ NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected) def",
"= [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name',",
"template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name =",
"['fake-app-1', 'fake-app-2', None] result = get_views_by_app(self.data) assert 'fake-app-3' not in",
"mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ): view_access =",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected",
"= get_views_by_app(self.data) assert 'fake-app-1' in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self,",
"'c')] result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self,",
"self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected = u'\\t'",
"role access tool is used: neither decorator, ' expected +=",
"view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True)",
"= [MockResolver()] self.regex = MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace =",
"' expected += u'Django role access tool is used: neither",
"def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type = None view_list =",
"= u'role-2' mock_view_access.roles.all.return_value = [role_1, role_2] result = analyze_by_role(mock_view_access) self.assertEqual(result,",
"['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps(",
"get_views_by_app(self.data) self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS",
"test_with_middleware_with_view_access_object_authorized(self): expected = u'View access is of type Authorized.' ViewAccess.objects.create(",
"): expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED',",
"class MockPattern: def __init__(self): self.regex = MockRegex() self.callback = 'fake-callback'",
"self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list",
"u'View access is of type By role.' expected += u'Roles",
"pattern_2 = MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result",
"= 'nested-namespace' class MockPatternDjango2: def __init__(self): self.pattern = '^fake-pattern/' self.callback",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called def test_view_analyzer_search_view_access_for_the_view_once( self,",
"report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' +",
"@patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ): view_access = Mock()",
"self.callback = 'fake-callback' self.name = 'fake-view-name' class MockPatternDjango2None: def __init__(self):",
"import TestCase as UnitTestCase from django.contrib.auth.models import Group from django.core.management",
"assert 'fake-app-1' in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ):",
"django.views.generic import TemplateView try: from unittest.mock import Mock, patch, MagicMock",
"= [('a', 'b', 'c', 'd', 'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings')",
"self, mock_objects ): expected = u'No Django roles access tool",
"('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self):",
"True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected = u'View",
"is required to return a dictionary with keys been installed",
"views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result, result) class",
"UnitTestWalkSiteURL(UnitTestCase): def setUp(self): self.pattern_1 = MockPattern() self.data = [self.pattern_1] def",
"= u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected =",
"self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert",
"[MockResolver()] self.regex = MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace = 'nested-namespace'",
"analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No roles",
"'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() nested_resolver = MockResolverDjangoNested()",
"= u'\\tFinish analyzing fake-app-name.' self._output.close_application_data('fake-app-name') self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self):",
"= '/fake-url/' expected = u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected +=",
"test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self):",
"assert 'fake-app-2' in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ):",
"'c3', None)] expected_result = [('a1', 'b2', 'c3')] result = get_views_by_app(data)",
"expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected = u'ERROR: View",
"= get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' +",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected)",
"setUp(self): self.data = [('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary(",
"1) def test_cvs_format_write_correct_csv_columns( self ): expected = u'App Name,Type,View Name,Url,Status,Status",
"def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected = u'View access is",
"'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result =",
"mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) assert 'fake-app-1' in",
"with access: role-1, role-2' mock_view_access.type = 'br' role_1 = Mock()",
"Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br')",
"self.assertEqual(result, expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected = u'\\t' +",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self ): expected =",
"= MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self):",
"self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected = u'ERROR: View",
"['fake-app-1'] data = [('a', 'b', 'c', 'd', 'e')] with self.assertRaises(TypeError):",
"expected = u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object(",
"True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected = u'View access is",
"self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_console_format_process_view_data_to_stdout_with_SUCCESS_style( self ): view_name",
"): view_access = Mock() view_access.type = 'br' mock_objects.filter.return_value = mock_objects",
"import BaseCommand from django.conf import settings from django.test import TestCase",
"def function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView): template_name",
"NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'DISABLED',",
") ] resolver = MockResolverDjango2None2() result = walk_site_url([resolver]) self.assertEqual(result, expected_result)",
"u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view,",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format =",
"walk_site_url([resolver]) self.assertEqual(result, expected_result) # def test_when_view_name_is_None(self): # expected_result = [",
"role.' expected += u'ERROR: No roles configured to access de",
"expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected = u'ERROR: No roles",
"view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self):",
"mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') assert mock_objects.first.called def",
"= get_views_by_app(self.data) assert 'fake-app-3' not in result class IntegratedTestGetViewsByApp(TestCase): def",
"MockPatternDjango2: def __init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name",
"expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function))",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self ): expected = u'Finish",
"self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] result =",
"mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] result = get_views_by_app(self.data) assert 'fake-app-1'",
"MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result, expected_result)",
"'^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace'",
"self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ): expected = u'\\tFinish",
"view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles(self): expected",
"= u'' view_access = ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access) self.assertEqual(result,",
"__init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-none'",
"self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called",
"type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self): expected =",
"[('a', 'b', 'c', 'd', 'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def",
"de view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value = 0 result =",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_close_application_data_to_string(self): expected = u'' self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row,",
"MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback',",
"def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result",
"self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name = None self.namespace",
"' expected += 'decorator, mixin, or middleware.' ViewAccess.objects.create( view='django_roles_access:middleware_view_func', type='pu')",
"= u'View access is of type By role.' expected +=",
"view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access)",
"= get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected =",
"text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called def",
"def test_no_django_roles_tools_used_application_type( self, mock_objects ): expected = u'No Django roles",
"expected += u'ERROR: No roles configured to access de view.'",
"result = view_access_analyzer('NOT_SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED(",
"self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name' app_type",
"def setUp(self): self.pattern_1 = MockPattern() self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self):",
"'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/'",
"[ # ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None # ) #",
"self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def",
"self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings ):",
"SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', 'fake-callback',",
"u'Roles with access: test1, test2' g1, created = Group.objects.get_or_create(name='test1') g2,",
"the view, ' expected += 'but no Django role access",
"to return a dictionary with keys been installed applications. \"\"\"",
"# print(result) # self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def setUp(self): self.url",
"= ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result)",
"1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some",
"@patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] result",
"u'View access is of type Public.' @access_by_role def function(): pass",
"NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex: def __init__(self): self.pattern = '^fake-regex-pattern/$'",
"receive the result of walk_site_url and is required to return",
"type Public.' @access_by_role def function(): pass view_access = Mock() view_access.type",
"import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view', None) result",
"expected) def test_without_middleware_with_view_access_object_public(self): expected = u'View access is of type",
"self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self ): expected =",
"view access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected =",
"expected += u'Start gathering information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone')",
"def test_internal_attributes_are_initialize(self): assert hasattr(self._output, '_row') and self._output._row == u'' assert",
"'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result",
"'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class UnitTestOutputReport(UnitTestCase): def setUp(self): self.patch_mock_stdout =",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected( self ): expected",
"view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type",
"django_roles_access.decorator import access_by_role from django_roles_access.mixin import RolesMixin from django_roles_access.models import",
"self.url_patterns = [MockPattern()] self.regex = MockRegexResolver() self.app_name = 'fake-app-name' self.namespace",
"'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url =",
"self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self ):",
"[('a', 'b', 'c', 'fake-app-1'), ('1', '2', '3', 'fake-app-2'), ('a1', 'b2',",
"None class MockResolverDjango2None2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns =",
"get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role')",
"self.pattern = '^fake-resolver/' class MockRegexResolverNested: def __init__(self): self.pattern = '^fake-nested-resolver/'",
"expected += u'\\t\\t{} does not have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type,",
"def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access') result =",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def",
"u'\\t' + SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self):",
"type='pu') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"= u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au')",
"test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected = u'ERROR: View access object exist",
"view_access = ViewAccess.objects.create(view='any-name', type='br') role_1, created = Group.objects.get_or_create(name='role-1') role_2, created",
"Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role(",
"class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected = u'ERROR: No roles configured",
"self.data = [('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self,",
"MockResolverDjango2None: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2None()] self.app_name",
"views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result",
"test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED',",
"self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access ): expected",
"role.' expected += u'Roles with access: test1, test2' g1, created",
"fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv'",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, 'fake-callback', 'fake-view-name',",
"to access de view.' view_access = ViewAccess.objects.create(view='any-name', type='br') result =",
"'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected",
"self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', 'django_roles_access')",
"app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = [] expected",
"'b', 'c', 'd', 'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application(",
"True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ):",
"analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects",
"= MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result = walk_site_url([resolver, nested_resolver]) self.assertEqual(result,",
"), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockResolver(),",
"expected = u'\\t' + NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"'fake-app-1' in result assert 'fake-app-2' in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists(",
"but no ' expected += u'Django role access tool is",
"django.core.management import BaseCommand from django.conf import settings from django.test import",
"View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self):",
"class MockResolver: def __init__(self): self.url_patterns = [MockPattern()] self.regex = MockRegexResolver()",
"def test_detect_access_is_not_by_role(self): expected = u'' view_access = ViewAccess.objects.create(view='any-name', type='pu') result",
"u'No Django roles access tool used. Access to view depends",
"['fake-view-list'] expected = u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list)",
"self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type = None view_list",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('Authorized', function, 'fake-view-name',",
"u'\\t' + NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result, expected)",
"= view_access_analyzer(None, 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self,",
"result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role",
"def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ): view_access = Mock() view_access.type =",
"applications. \"\"\" def setUp(self): self.data = [('a', 'b', 'c', 'fake-app-1')]",
"self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name = u'fake-view-name'",
"class MockRegex: def __init__(self): self.pattern = '^fake-regex-pattern/$' class MockRegexResolver: def",
"+ NONE_TYPE_DEFAULT result = view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/',",
"get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected = u'\\t' + SECURED_DEFAULT",
"app_name = u'fake-app-name' app_type = None view_list = ['fake-view'] expected",
"): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result = get_views_by_app(self.data) self.assertIsInstance(result, dict)",
"analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self, mock_view_access ): expected =",
"expected) self.assertEqual(result, expected) def test_report_for_application_type_DISABLED(self): expected = u'\\t' + DISABLED_DEFAULT",
"implementation.' def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer(",
"= 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected",
"expected = u'\\t' + NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result, expected)",
"def setUp(self): self.data = [('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def",
"= ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role(self):",
"0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self, mock_view_access",
"expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected = u'\\t' + NONE_TYPE_DEFAULT",
"self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called def test_console_format_use_style_with_vaa_result(self): self._output.write_view_access_analyzer(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'\\t\\tsome text')",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format =",
"[ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None ) ] resolver = MockResolverDjango2None2()",
"test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result,",
"def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', 'fake-callback',",
"views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected",
"'fake-app-2' in result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS",
"True) self.assertEqual(expected, result) def test_with_middleware_NOT_SECURED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result =",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self ): expected = u'App",
"access.' self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected = u'\\n'",
"view: {}'.format(view_name) expected += u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected)",
"'fake-view-name', True) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected",
"app_type = u'fake-app-type' view_list = ['fake-view-list'] expected = u'{},{},'.format(app_name, app_type,",
"mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected = u'\\t' +",
"self.callback = 'fake-callback' self.name = 'fake-view-name' class MockResolver: def __init__(self):",
"resolver = MockResolverDjango2None2() # result = walk_site_url([resolver]) # print(result) #",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING:",
"self ): expected = u'\\t' + NONE_TYPE_DEFAULT result = view_access_analyzer(",
"analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected = u'ERROR:",
"the view, but no ' expected += u'Django role access",
"{}'.format(view_name) expected += u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"test_view_access_type_by_role_call_analyze_by_role_once( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type =",
"u'ERROR: View access object exist for the view, but no",
"text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def",
"Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self):",
"result @patch('django_roles_access.utils.settings') def test_values_of_returned_dictionary_keys_are_lists( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"'^fake-resolver/' class MockRegexResolverNested: def __init__(self): self.pattern = '^fake-nested-resolver/' class MockPattern:",
"self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ): expected = u'Roles",
"self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type = 'br'",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(mock_analyze_by_role.call_count, 1)",
"for the view, ' expected += 'but no Django role",
"type By role.' expected += u'ERROR: No roles configured to",
"self.name = 'fake-view-name' class MockResolver: def __init__(self): self.url_patterns = [MockPattern()]",
"def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected = u'\\t' + SECURED_DEFAULT",
"walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role',",
"test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout assert self._output.style == self.mock_style def",
"and is required to return a dictionary with keys been",
"test_csv_format_write_view_access_analyzer_with_ERROR_with_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Error,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report')",
"'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result =",
"+= u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"= u'\\t' + SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result, expected) def",
"= u'fake-app-name' app_type = u'fake-app-type' view_list = [] expected =",
"'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ): expected",
"self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start()",
"def test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None )",
"[('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/', 'fake-view-2', 'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self):",
"import_module from unittest import TestCase as UnitTestCase from django.contrib.auth.models import",
"self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def",
"app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name'",
"Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_NOT_SECURED( self, mock_objects ): expected = u'\\t'",
"test_console_format_use_ERROR_style_for_output_if_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake",
"MockResolverDjango2None2() # result = walk_site_url([resolver]) # print(result) # self.assertEqual(result, expected_result)",
"self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout assert self._output.style",
") ] resolver = MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result =",
"= walk_site_url([resolver]) # print(result) # self.assertEqual(result, expected_result) class IntegratedTestWalkSiteURL(TestCase): def",
"None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverNested()",
"self.name = 'fake-view-none' class MockResolverDjango2: def __init__(self): self.pattern = '^fake-resolver/'",
"access de view.' mock_view_access.type = 'br' mock_view_access.roles.count.return_value = 0 result",
"= 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result,",
"self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_to_stdout_with_SUCCESS_style(self): app_name = u'fake-app-name'",
"result = get_views_by_app(self.data) self.assertIsInstance(result['fake-app-1'], list) self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element(",
"self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self): app_name =",
"= 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverNested: def __init__(self): self.url_patterns",
"= u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name,",
"result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the result of walk_site_url",
"): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] result = get_views_by_app(self.data) assert",
"): expected = u'View access is of type Public.' view_access",
"SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected =",
"test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result =",
"access: role-1, role-2' mock_view_access.type = 'br' role_1 = Mock() role_1.name",
"{} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"= u'\\t' + PUBLIC_DEFAULT @access_by_role def function(): pass mock_objects.filter.return_value =",
"= get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected = u'\\t' +",
"u'fake-app-type' view_list = ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected +=",
"self._output.write_footer() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_footer_to_string(self): expected = u'\\n' self._output.set_format('csv')",
"created = Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save()",
"UnitTestCase from django.contrib.auth.models import Group from django.core.management import BaseCommand from",
"Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access) self.assertEqual(result, expected) def",
"NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None,",
"assert self._output._format == 'console' def test_set_format(self): self._output.set_format('csv') assert self._output._format ==",
"def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list =",
"def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') expected = u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report')",
"@patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2',",
"OutputReport) class MockRegex: def __init__(self): self.pattern = '^fake-regex-pattern/$' class MockRegexResolver:",
"type='br') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected)",
"= mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name')",
"+ PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"walk_site_url(self.data) self.assertIsInstance(result, list) def test_first_param_list_of_pattern_and_view(self): result = walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/',",
"expected = u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type By",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') try: self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str)",
"self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type =",
"view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result,",
"mock_objects mock_objects.first.return_value = None result = view_access_analyzer(None, 'fake-callback', 'fake-view-name', True)",
"test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type By role.'",
"= MockPattern() self.data = [self.pattern_1] def test_second_param_is_optional_return_a_list(self): result = walk_site_url(self.data)",
"' expected += u'on its implementation.' def function(): pass mock_objects.filter.return_value",
"self.assertEqual(result, expected) def test_no_django_roles_tools_used_application_type( self, mock_objects ): expected = u'No",
"'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ]",
"result = view_access_analyzer( None, views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def",
"u'\\n\\t\\tView url: {}'.format(url) self._output.process_view_data(view_name, url) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self):",
"self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_type(self): app_name =",
"self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC( self, mock_objects ): expected = u'\\t'",
"'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout",
"expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking view access.' self._output.write_footer()",
"from django.core.management import BaseCommand from django.conf import settings from django.test",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected = u'View",
"= mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC', function, 'fake-view-name',",
"def test_without_middleware_with_view_access_object_public(self): expected = u'View access is of type Public.'",
"views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result",
"+ SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected",
"self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access is of",
"nested_resolver]) self.assertEqual(result, expected_result) def test_when_url_namespace_is_None(self): expected_result = [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback',",
"u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view-list'] expected = u'{},{},'.format(app_name,",
"' expected += 'but no Django role access tool is",
"= u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings",
"'b2', 'c3')] result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict(",
"test_with_middleware_with_view_access_object_public(self): expected = u'View access is of type Public.' ViewAccess.objects.create(",
"= None class MockResolverDjango2None2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns",
"= get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected = u'\\t' +",
"patch, MagicMock except: from mock import Mock, patch from django_roles_access.decorator",
"def test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type",
"'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result,",
"'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name',",
"OutputReport(self.mock_stdout, self.mock_style) def tearDown(self): self.patch_mock_stdout.stop() self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout",
"{}\\n'.format(app_name) expected += u'\\t\\t{} is {} type.'.format(app_name, app_type) self._output.process_application_data(app_name, app_type,",
"'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format",
"self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result",
"self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self ): expected =",
"test_view_access_type_by_role_call_analyze_by_role_with_view_access( self, mock_analyze_by_role, mock_objects ): view_access = Mock() view_access.type =",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('Authorized', function,",
"'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access",
"self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1'] result = get_views_by_app(self.data) assert",
"roles access middleware is active: False.\\n' self._output.set_format('csv') self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"def test_cvs_format_write_correct_header( self, mock_timezone ): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header()",
"test_cvs_format_write_correct_correct_middleware_status( self ): expected = u'Django roles access middleware is",
"self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern()",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type', function,",
"not in result class IntegratedTestGetViewsByApp(TestCase): def setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns",
"'pu' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access result = view_access_analyzer('fake-app-type',",
"= [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name'",
"= 'fake-callback' self.name = 'fake-view-name' class MockPatternDjango2None: def __init__(self): self.pattern",
"def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name =",
"'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected",
"test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern = 'fake-regex-pattern-2/' pattern_2.callback = 'fake-view-2'",
"u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result =",
"test1, test2' g1, created = Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2')",
"expected = u'\\n\\t\\tAnalysis for view: {}'.format(view_name) expected += u'\\n\\t\\tView url:",
"u'' assert hasattr(self._output, '_format') and self._output._format == \\ 'console' def",
"does not have configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"result = view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' +",
"self.url_patterns = [MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_view_data(self): view_name = u'fake-view-name' url = '/fake-url/'",
"view_access = ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result =",
"= '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-none' class MockResolverDjango2:",
"with access: role-1, role-2' view_access = ViewAccess.objects.create(view='any-name', type='br') role_1, created",
"[ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' )",
"'django_roles_access:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result",
"test_detect_access_is_not_by_role(self): expected = u'' view_access = ViewAccess.objects.create(view='any-name', type='pu') result =",
"'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called",
"django_roles_access.models import ViewAccess from tests import views from django_roles_access.utils import",
"@patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ): view_access = Mock()",
"self.assertIn(expected_result, result) def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access')",
"expected = u'ERROR: No roles configured to access de view.'",
"self.assertEqual(result, expected) def test_detect_access_is_not_by_role_without_roles( self, mock_view_access ): expected = u'ERROR:",
"Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class',",
"class Aview(TemplateView): template_name = 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def",
"no ' expected += u'Django role access tool is used:",
"assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' +",
"test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake",
"result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_PUBLIC(",
"app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name'",
"result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result =",
"MockRegexResolverNested: def __init__(self): self.pattern = '^fake-nested-resolver/' class MockPattern: def __init__(self):",
"dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"= [('a', 'b', 'c')] result = get_views_by_app(data) self.assertEqual(expected_result, result['fake-app-1']) @patch('django_roles_access.utils.settings')",
"walk_site_url(self.data) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 =",
"expected = u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1)",
"is of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu') result = view_access_analyzer(",
"result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-regex-pattern-2/',",
"setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_not_declared_app_are_recognized_as_undefined_app(self): expected_result = ('direct_access_view/', views.protected_view_by_role,",
"self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self): expected = u'\\t' + SECURED_DEFAULT result",
"result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result =",
"ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='au') result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False)",
"self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class UnitTestWalkSiteURL(UnitTestCase): def setUp(self):",
"mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def",
"self.assertIsInstance(result, unicode) except: self.assertIsInstance(result, str) def test_view_analyzer_search_view_access_for_the_view( self, mock_objects ):",
"+ DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected = u'View access is of",
"self._output._row == u'' assert hasattr(self._output, '_format') and self._output._format == \\",
"'fake-namespace' class MockResolverNested: def __init__(self): self.url_patterns = [MockResolver()] self.regex =",
"'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected =",
"view depends ' expected += u'on its implementation.' def function():",
"# ] # resolver = MockResolverDjango2None2() # result = walk_site_url([resolver])",
"de view.' view_access = ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result,",
"UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the result of walk_site_url and is",
"expected) def test_no_django_roles_tools_used_no_application_type( self, mock_objects ): expected = u'No Django",
"report') assert self.mock_style.WARNING.called def test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t'",
"'django_roles_access:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_view_with_namespace_are_added_with_correct_app_name(self): expected_result =",
"+ SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result =",
"'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app( self ):",
"required to return a dictionary with keys been installed applications.",
"expected = u'\\t' + PUBLIC_DEFAULT @access_by_role def function(): pass mock_objects.filter.return_value",
"is of type Public.' @access_by_role def function(): pass view_access =",
"information.' self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone",
"class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects ): view_access = Mock()",
"__init__(self): self.pattern = '^fake-resolver/' class MockRegexResolverNested: def __init__(self): self.pattern =",
"def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None]",
"expected = u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"self, mock_timezone ): mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date')",
"self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR:",
"self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.mock_style.ERROR.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_reset_OutputFormater_row( self ):",
"app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view'] expected",
"test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected = u'View access is of",
"def test_returns_a_dictionary( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2'] result",
"u'ERROR: No roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class',",
"'br' role_1 = Mock() role_1.name = u'role-1' role_2 = Mock()",
"= patch.object(BaseCommand(), 'style') self.patch_mock_style = patch.object(BaseCommand(), 'stdout') self.mock_stdout = self.patch_mock_stdout.start()",
"result = view_access_analyzer( None, views.middleware_view, 'django_roles_access:middleware_view_func', False) self.assertEqual(result, expected) class",
"views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self):",
"= u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_correct_middleware_status(",
"self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace",
"expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback',",
"access tool is used: neither ' expected += 'decorator, mixin,",
"Mock() view_access.type = 'br' mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access",
"django.conf import settings from django.test import TestCase from django.views.generic import",
"test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) @patch('django_roles_access.utils.timezone') def test_cvs_format_write_correct_header( self, mock_timezone ):",
"test_view_analyzer_search_view_access_with_view_name( self, mock_objects ): view_access = Mock() view_access.type = 'pu'",
"self.patch_mock_style.stop() def test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout assert self._output.style ==",
"def test_detect_view_is_decorated(self): @access_by_role def function(): pass self.assertTrue(check_django_roles_is_used(function)) def test_detect_view_is_not_decorated(self): def",
"('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self):",
"True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected =",
"= ViewAccess.objects.create(view='any-name', type='br') role_1, created = Group.objects.get_or_create(name='role-1') role_2, created =",
"False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected = u'View access is",
"assert hasattr(self._output, '_row') and self._output._row == u'' assert hasattr(self._output, '_format')",
"('1', '2', '3', 'fake-app-2'), ('a1', 'b2', 'c3', None)] expected_result =",
"test_csv_format_write_view_access_analyzer_with_Normal_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_csv_format_write_view_access_analyzer_with_Normal_to_style(self):",
"'fake-view-name', None)]) def test_param_list_with_pattern_and_resolver_django_1(self): expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name',",
"fake report') assert self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t'",
"'fake-app-name' ) ] resolver = MockResolverNested() result = walk_site_url([self.pattern_1, resolver])",
"@patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2']",
"= u'fake-app,fake-type,fake-view,fake-url,Normal,fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,')",
"def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self): self._output.write(u'some text')",
"= [ ('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None ) ] resolver =",
"= view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self):",
"analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected = u'Roles with access:",
"type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_process_app_data_without_views(self): app_name",
"def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ),",
"self, mock_objects ): expected = u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value =",
"walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self): expected_result = [ ('fake-pattern/',",
"def test_found_included_view_with_namespace(self): expected_result = ('role-included2/view_by_role/', views.protected_view_by_role, 'app-ns2:view_protected_by_role', 'django_roles_access') result =",
"expected) def test_with_middleware_with_view_access_object_authorized(self): expected = u'View access is of type",
"output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_stdout.write.called def test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some",
"= ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer(",
"NOT_SECURED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('NOT_SECURED',",
"view_list = [] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{}",
"False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected = u'ERROR:",
"def test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text')",
"MockRegexResolverNested() self.app_name = 'fake-app-name' self.namespace = 'nested-namespace' class MockPatternDjango2: def",
"def test_initial_with_parameter(self): assert self._output.stdout == self.mock_stdout assert self._output.style == self.mock_style",
"get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['django_roles_access']) def test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_'",
"self.assertIsInstance(result['fake-app-2'], list) @patch('django_roles_access.utils.settings') def test_receive_list_of_tuples_with_4_element( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"u'View access is of type Authorized.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='au') result",
"type='pu') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected =",
"self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name'",
"self, mock_objects ): view_access = Mock() view_access.type = 'pu' mock_objects.filter.return_value",
"= ['fake-view'] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} has",
"app_name = u'fake-app-name' app_type = u'fake-app-type' view_list = ['fake-view-list'] expected",
"expected_result = [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback',",
"'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self, mock_objects ):",
"expected += 'but no Django role access tool is used:",
"mock_timezone.now.return_value = 'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"[] expected = u'\\tAnalyzing: {}\\n'.format(app_name) expected += u'\\t\\t{} is {}",
"self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some text') def test_console_format_write_correct_header_to_stdout_with_SUCCESS_style( self",
"used. Access to view depends ' expected += u'on its",
"expected = u'\\t' + DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected)",
"test_view_analyzer_search_view_access_for_the_view_once( self, mock_objects ): view_access = Mock() view_access.type = 'pu'",
"def test_cvs_format_process_application_data_without_type_to_string(self): app_name = u'fake-app-name' app_type = None view_list =",
"= MockRegex() self.callback = 'fake-callback' self.name = 'fake-view-name' class MockResolver:",
"self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake report') def test_console_format_use_WARNING_style_for_output_if_warning_in_vaa(self):",
"self.mock_stdout = self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style)",
"django_roles_access.mixin import RolesMixin from django_roles_access.models import ViewAccess from tests import",
"test_write_method_use_SUCCESS_style_for_output(self): self._output.write(u'some text') assert self.mock_style.SUCCESS.called def test_write_method_use_style_with_received_argument(self): self._output.write(u'some text') self.mock_style.SUCCESS.assert_called_once_with(u'some",
"'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_with_roles(self): expected =",
"self.assertIn(expected, self._output._row) # View_access_analyzer output. def test_console_format_write_vaa_to_stdout(self): self._output.write_view_access_analyzer(u'some text') assert",
"+ PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def",
"from django_roles_access.utils import (walk_site_url, get_views_by_app, view_access_analyzer, get_view_analyze_report, check_django_roles_is_used, analyze_by_role, APP_NAME_FOR_NONE,",
"= self.patch_mock_stdout.start() self.mock_style = self.patch_mock_style.start() self._output = OutputReport(self.mock_stdout, self.mock_style) def",
"== self.mock_stdout assert self._output.style == self.mock_style def test_internal_attributes_are_initialize(self): assert hasattr(self._output,",
"Aview(RolesMixin, TemplateView): template_name = 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView):",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) assert mock_analyze_by_role.called @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role_once(",
"'br' mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def",
"] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_1(self): expected_result",
"mock_objects ): view_access = Mock() view_access.type = 'br' mock_objects.filter.return_value =",
"u'ERROR: No roles configured to access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role',",
"'fake-namespace:fake-view-name', 'fake-app-name' ) ] resolver = MockResolverDjango2() result = walk_site_url([MockPatternDjango2(),",
"'csv' def test_add_to_row(self): self._output.add_to_row('text') self._output.add_to_row('other') self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def",
"False.\\n' self._output.write_middleware_status(False) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_end_of_header( self ): expected",
"self._output.set_format('csv') self._output.close_application_data('fake-app-name') self.assertEqual(self._output._row, expected) def test_console_format_write_footer_to_stdout_with_SUCCESS_style(self): expected = u'End checking",
"@patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects ): view_access =",
"): expected = u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value",
"= view_access_analyzer('DISABLED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected) def test_no_view_access_object_and_site_active_app_type_SECURED( self,",
"result = view_access_analyzer('fake-app-type', function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used(",
"test_without_middleware_no_view_access_object_and_view_protected_without_app( self ): expected = u'\\t' + NONE_TYPE_DEFAULT result =",
"expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name',",
"view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def",
"mock_view_access ): expected = u'ERROR: No roles configured to access",
"with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings ): mock_settings.INSTALLED_APPS",
"get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class TestCheckDjangoRolesIsUsed(UnitTestCase): def test_detect_view_is_decorated(self): @access_by_role def function():",
"class MockRegexResolverNested: def __init__(self): self.pattern = '^fake-nested-resolver/' class MockPattern: def",
"1) def test_cvs_format_process_application_data_to_string(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list",
"= 'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access",
"import settings from django.test import TestCase from django.views.generic import TemplateView",
"= walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_1(self): expected_result = [",
"test_csv_format_write_view_access_analyzer_with_ERROR_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('ERROR: fake-report') self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"been installed applications. \"\"\" def setUp(self): self.data = [('a', 'b',",
"function, 'fake-view-name', False) self.assertEqual(result, expected) def test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ):",
"'c3', None)] expected_result = [('a', 'b', 'c')] result = get_views_by_app(data)",
"('fake-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'fake-view-none', None ) ] resolver = MockResolverDjango2None2() result",
"'fake-app-2', None] data = [('a', 'b', 'c', 'fake-app-1'), ('1', '2',",
"{}\\n'.format(app_name) expected += u'\\t\\t{} has no type.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list)",
"= [MockPatternDjango2None()] self.app_name = None self.namespace = None class MockResolverDjango2None2:",
"'fake-date' self._output.set_format('csv') self._output.write_header() self.mock_style.SUCCESS.assert_called_once_with(u'Reported: fake-date') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_write_correct_middleware_status_and_end_of_header( self",
"('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ]",
"test_write_method_use_stdout_write_once(self): self._output.write(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_write_method_use_SUCCESS_style_for_styling_output(self): self._output.write(u'some text') self.mock_stdout.write.assert_called_once_with(",
"1) def test_console_format_process_app_data_without_views(self): app_name = u'fake-app-name' app_type = u'fake-app-type' view_list",
"self._output._format = 'csv' self._output.write_view_access_analyzer(u'fake-report') self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format =",
"unittest.mock import Mock, patch, MagicMock except: from mock import Mock,",
"self ): view_name = u'fake-view-name' url = '/fake-url/' expected =",
"1) def test_console_format_process_app_data_without_type(self): app_name = u'fake-app-name' app_type = None view_list",
"): expected = u'Finish gathering information.' self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1)",
"= Group.objects.get_or_create(name='role-1') role_2, created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result",
"app_type = u'fake-app-type' view_list = [] expected = u'\\tAnalyzing: {}\\n'.format(app_name)",
"def test_with_middleware_with_view_access_object_authorized(self): expected = u'View access is of type Authorized.'",
"self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self): expected = u'\\t' + NOT_SECURED_DEFAULT result",
"= 'dummyTemplate.html' self.assertTrue(check_django_roles_is_used(Aview)) def test_detect_view_not_use_mixin(self): class Aview(TemplateView): template_name = 'dummyTemplate.html'",
"def test_middleware_not_used_view_access_object_exist_and_dr_tools_used( self, mock_objects ): expected = u'View access is",
"view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') self.assertEqual(mock_objects.filter.call_count, 1) def test_view_analyzer_search_view_access_with_view_name( self,",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create(",
"= u'fake-app-type' view_list = ['fake-view-list'] expected = u'{},{},'.format(app_name, app_type, view_list)",
"= u'Roles with access: role-1, role-2' mock_view_access.type = 'br' role_1",
"True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self, mock_objects ): expected = u'\\t'",
"self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_write_correct_csv_columns( self ): expected = u'App Name,Type,View",
"views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected = u'View",
"u'fake-app-type' view_list = [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type,",
"def test_without_middleware_with_view_access_object_and_view_not_protected( self ): expected = u'ERROR: View access object",
"from django.contrib.auth.models import Group from django.core.management import BaseCommand from django.conf",
"'dummyTemplate.html' self.assertFalse(check_django_roles_is_used(Aview)) @patch('django_roles_access.utils.ViewAccess') class UnitTestAnalyzeByRoleAccess(UnitTestCase): def test_detect_access_is_by_role( self, mock_view_access ):",
"= None result = view_access_analyzer('SECURED', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"'fake-app-name' ) ] result = walk_site_url([MockPatternDjango2(), MockResolverDjangoNested()]) self.assertEqual(result, expected_result) def",
"True) self.assertEqual(result, expected) @patch('django_roles_access.utils.analyze_by_role') def test_view_access_type_by_role_call_analyze_by_role( self, mock_analyze_by_role, mock_objects ):",
"[MockPattern()] self.regex = MockRegexResolver() self.app_name = 'fake-app-name' self.namespace = 'fake-namespace'",
"class MockPatternDjango2None: def __init__(self): self.pattern = '^fake-pattern/' self.callback = 'fake-callback'",
"[('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None)]) def test_first_param_list_of_patterns_and_views(self): pattern_2 = MockPattern() pattern_2.regex.pattern",
"test_nested_namespace_are_added_with_correct_app_name(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url))",
"self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('fake-report') self.assertEqual(self._output._row, u'fake-app,fake-type,') def test_console_format_close_application_data_to_stdout_with_SUCCESS_style( self",
"type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name",
"= view_access result = view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) self.assertEqual(result, expected)",
"= '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace =",
"] resolver = MockResolverDjango2() nested_resolver = MockResolverDjangoNested() result = walk_site_url([resolver,",
"data = [('a', 'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def",
"mock_objects ): expected = u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects",
"= view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_no_view_access_object_and_view_protected_without_app(",
"access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'SECURED',",
"self ): expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer(",
"[MockPatternDjango2()] self.app_name = 'fake-app-name' self.namespace = 'fake-namespace' class MockResolverDjango2None: def",
"views.protected_view_by_role, 'direct_access_view', None) result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self):",
"self.pattern = '^fake-pattern/' self.callback = 'fake-callback' self.name = 'fake-view-name' class",
"= MockResolverNested() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_resolver_django_2(self):",
"u'Django role access tool is used: neither decorator, ' expected",
"self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def test_console_format_use_SUCCESS_style_for_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') assert self.mock_style.SUCCESS.called",
"expected = u'\\t' + SECURED_DEFAULT result = get_view_analyze_report('SECURED') self.assertEqual(result, expected)",
"None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name', 'fake-app-name' ) ] result = walk_site_url([MockPatternDjango2(),",
"result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def test_views_without_namespace_are_added_with_app_name_in_view_name(self): expected_result = ('role-included[135]/view_by_role/',",
"expected_result = [ ('fake-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-nested-resolver/fake-resolver/fake-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name',",
"# ('fake-resolver/fake-pattern/', # 'fake-callback', 'fake-view-name', None # ) # ]",
"= analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self): expected =",
"self.assertEqual(result, u'\\t' + NOT_SECURED_DEFAULT) def test_with_middleware_DISABLED_with_view_access_object(self): ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='pu') result",
"expected = u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count,",
"def __init__(self): self.pattern = '^fake-regex-pattern/$' class MockRegexResolver: def __init__(self): self.pattern",
"def test_no_view_access_object_and_site_active_app_type_DISABLED( self, mock_objects ): expected = u'\\t' + DISABLED_DEFAULT",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_with_roles(self): expected = u'View access",
"from django_roles_access.mixin import RolesMixin from django_roles_access.models import ViewAccess from tests",
"= ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role', 'roles-app-name') result = walk_site_url(self.url) self.assertIn(expected_result,",
"= u'fake-app-type' view_list = [] expected = u'fake-app-name,fake-app-type,,,,,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name,",
"self.mock_style.SUCCESS.assert_called_once_with(expected) def test_csv_format_write_view_access_analyzer_with_WARNING_to_stdout(self): self._output.add_to_row('fake-app,fake-type,fake-view,fake-url,') self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.assertEqual(self.mock_stdout.write.call_count,",
"view_access_analyzer( 'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def",
"view='django_roles_access:middleware_view_class', type='br') result = view_access_analyzer( 'NOT_SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result,",
"self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected = u'\\t' +",
"MockPattern: def __init__(self): self.regex = MockRegex() self.callback = 'fake-callback' self.name",
"self, mock_objects ): expected = u'ERROR: View access object exist",
"] resolver = MockResolverNested() result = walk_site_url([self.pattern_1, resolver]) self.assertEqual(result, expected_result)",
"created = Group.objects.get_or_create(name='role-2') view_access.roles.add(role_1) view_access.roles.add(role_2) view_access.save() result = analyze_by_role(view_access) self.assertEqual(result,",
"pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result = view_access_analyzer('PUBLIC',",
"self, mock_view_access ): expected = u'ERROR: No roles configured to",
"None view_list = ['fake-view-list'] expected = u'fake-app-name,no type,'.format(app_name) self._output.set_format('csv') self._output.process_application_data(app_name,",
"= [ ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' ), ('fake-nested-resolver/fake-resolver/fake-regex-pattern/', 'fake-callback', 'nested-namespace:fake-namespace:fake-view-name',",
"self.assertIsInstance(result, dict) @patch('django_roles_access.utils.settings') def test_returns_a_dictionary_with_all_installed_apps( self, mock_settings ): mock_settings.INSTALLED_APPS =",
"= view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def test_without_middleware_without_view_access_object_and_view_protected(",
"expected) def test_report_for_application_type_DISABLED(self): expected = u'\\t' + DISABLED_DEFAULT result =",
"'direct_access_view', None) result = walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result",
"= ViewAccess.objects.create(view='any-name', type='pu') result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self):",
"None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name' )] resolver = MockResolver() result",
"self.assertEqual(result, expected) def test_without_middleware_with_view_access_object_public(self): expected = u'View access is of",
"result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role_with_roles( self, mock_view_access ):",
"mock_objects ): expected = u'\\t' + PUBLIC_DEFAULT @access_by_role def function():",
"u'' mock_view_access.type = 'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def",
"def function(): pass mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"walk_site_url(self.url) self.assertIn(expected_result, result) class UnitTestGetViewsByApp(UnitTestCase): \"\"\" get_views_by_app receive the result",
"result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected = u'\\t' + NONE_TYPE_DEFAULT",
"= u'\\t' + PUBLIC_DEFAULT result = get_view_analyze_report('PUBLIC') self.assertEqual(result, expected) class",
"expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [ ('fake-resolver/fake-pattern/', 'fake-callback', 'fake-namespace:fake-view-name', 'fake-app-name'",
"'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ): expected = u'View",
"test_detect_view_is_not_decorated(self): def function(): pass self.assertFalse(check_django_roles_is_used(function())) def test_detect_view_use_mixin(self): class Aview(RolesMixin, TemplateView):",
"PUBLIC_DEFAULT, NONE_TYPE_DEFAULT, DISABLED_DEFAULT, OutputReport) class MockRegex: def __init__(self): self.pattern =",
"= walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result = [",
"[('a', 'b', 'c', 'fake-app-1')] @patch('django_roles_access.utils.settings') def test_returns_a_dictionary( self, mock_settings ):",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self,",
"= u'View access is of type Public.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='pu')",
"'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ):",
"walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_included_view_without_namespace(self): expected_result = ('role-included[135]/view_by_role/', views.protected_view_by_role, 'django_roles_access:view_protected_by_role',",
"'fake-app-1' in result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS",
"test_console_format_use_stdout_write_once_with_vaa(self): self._output.write_view_access_analyzer(u'some text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with(",
"'c', 'fake-app-1'), ('1', '2', '3', 'fake-app-2'), ('a1', 'b2', 'c3', None)]",
"u'App Name,Type,View Name,Url,Status,Status description' self._output.set_format('csv') self._output.write_end_of_head() self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def",
"ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') view_access.roles.add(g1) view_access.roles.add(g2) view_access.save() result = view_access_analyzer( 'SECURED',",
"expected = u'' mock_view_access.type = 'pu' result = analyze_by_role(mock_view_access) self.assertEqual(result,",
"self.pattern = '^fake-nested-resolver/' self.url_patterns = [MockResolverDjango2()] self.app_name = 'fake-app-name' self.namespace",
"= 'br' mock_view_access.roles.count.return_value = 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected)",
"result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(expected, result) def",
"result = view_access_analyzer( 'SECURED', views.protected_view_by_role, 'django_roles_access:view_protected_by_role', False) self.assertEqual(result, expected) def",
"self.assertIn('text', self._output._row) self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called",
"configured views.'.format(app_name) self._output.process_application_data(app_name, app_type, view_list) self.mock_style.SUCCESS.assert_called_once_with(expected) self.assertEqual(self.mock_stdout.write.call_count, 1) def test_cvs_format_process_application_data_to_string(self):",
"def __init__(self): self.pattern = '^fake-resolver/' class MockRegexResolverNested: def __init__(self): self.pattern",
"view_access_analyzer( 'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_without_middleware_with_view_access_object(self): expected",
"as UnitTestCase from django.contrib.auth.models import Group from django.core.management import BaseCommand",
"= u'ERROR: No roles configured to access de view.' view_access",
"'DISABLED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self):",
"u'fake-app-type' view_list = ['fake-view-list'] expected = u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv')",
"expected = u'{},{},'.format(app_name, app_type, view_list) self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected,",
"u'\\t' + NONE_TYPE_DEFAULT result = get_view_analyze_report(None) self.assertEqual(result, expected) def test_report_for_application_type_NOT_SECURED(self):",
"def test_view_analyzer_return_a_report( self, mock_objects ): view_access = Mock() view_access.type =",
"def test_without_middleware_with_view_access_object_with_roles(self): expected = u'View access is of type By",
"self.assertIn('other', self._output._row) def test_write_method_write_to_stdout(self): self._output.write(u'some text') assert self.mock_stdout.write.called def test_write_method_use_stdout_write_once(self):",
"'fake-view-2' result = walk_site_url([self.pattern_1, pattern_2]) self.assertEqual(result, [('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None),",
"expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report( self, mock_objects ): view_access",
"result = analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase): def test_view_analyzer_return_a_report(",
"'c3')] result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self,",
"expected = u'\\t' + SECURED_DEFAULT result = view_access_analyzer( 'SECURED', views.MiddlewareView.as_view,",
"result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def test_param_list_with_resolver_get_app_name_and_view_name_django_2(self): expected_result =",
"mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] result = get_views_by_app(self.data) assert 'fake-app-3'",
"' expected += u'mixin, or middleware.' def function(): pass view_access",
"access de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer( 'SECURED',",
"self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_views(self): app_name = u'fake-app-name'",
"'d', 'e')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings",
"expected = u'\\t' + NONE_TYPE_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value =",
"test_detect_access_is_not_by_role_without_roles(self): expected = u'ERROR: No roles configured to access de",
"walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result = [ ('fake-pattern/',",
"ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) @patch('django_roles_access.utils.ViewAccess.objects') class UnitTestViewAnalyzer(UnitTestCase):",
"expected = u'View access is of type By role.' expected",
"def __init__(self): self.pattern = '^fake-nested-resolver/' class MockPattern: def __init__(self): self.regex",
"= view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True) mock_analyze_by_role.assert_called_once_with(view_access) def test_no_view_access_object_for_the_view_and_site_active_no_app_type( self,",
"'SECURED', views.MiddlewareView.as_view, 'django_roles_access:middleware_view_class', True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_authorized(self): expected =",
"= walk_site_url(self.url) self.assertIn(expected_result, result) def test_found_nested_access_view(self): expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role,",
"): expected = u'Roles with access: role-1, role-2' mock_view_access.type =",
"OutputReport() def test_default_output_format_is_correct_type(self): assert self._output._format == 'console' def test_set_format(self): self._output.set_format('csv')",
"result['fake-app-1']) @patch('django_roles_access.utils.settings') def test_can_work_with_no_declared_application_name( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"'b', 'c')] with self.assertRaises(TypeError): get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_5_element( self, mock_settings",
"setUp(self): self.url = import_module(settings.ROOT_URLCONF).urlpatterns def test_found_direct_access_view(self): expected_result = ('direct_access_view/', views.protected_view_by_role,",
"= u'\\t' + NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected) self.assertEqual(result,",
"u'fake-app,fake-type,fake-view,fake-url,Warning,' \\ u'fake-report\\n' self._output._format = 'csv' self._output.write_view_access_analyzer('WARNING: fake-report') self.mock_style.WARNING.assert_called_once_with(expected) def",
"u'\\t' + DISABLED_DEFAULT result = get_view_analyze_report('DISABLED') self.assertEqual(result, expected) def test_report_for_application_type_SECURED(self):",
"= u'View access is of type Public.' @access_by_role def function():",
"class MockResolverDjango2: def __init__(self): self.pattern = '^fake-resolver/' self.url_patterns = [MockPatternDjango2()]",
"configured to access de view.' ViewAccess.objects.create( view='django_roles_access:middleware_view_class', type='br') result =",
"[('a1', 'b2', 'c3')] result = get_views_by_app(data) self.assertEqual(expected_result, result[APP_NAME_FOR_NONE]) @patch('django_roles_access.utils.settings') def",
"de view.' ViewAccess.objects.create( view='django_roles_access:view_protected_by_role', type='br') result = view_access_analyzer( 'SECURED', views.protected_view_by_role,",
"mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = view_access view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', True)",
"test_middleware_not_used_view_access_object_exist_and_dr_tools_not_used( self, mock_objects ): expected = u'ERROR: View access object",
"result @patch('django_roles_access.utils.settings') def test_raise_type_error_if_receive_list_of_tuples_with_3_element( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1']",
"expected = u'Django roles access middleware is active: False.\\n' self._output.write_middleware_status(False)",
"expected) def test_middleware_not_used_dr_tools_are_used_no_view_access_object( self, mock_objects ): expected = u'\\t' +",
"get_views_by_app(data) @patch('django_roles_access.utils.settings') def test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1',",
"= u'\\t' + PUBLIC_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None",
"= 0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) def test_detect_access_is_not_by_role( self,",
"self, mock_objects ): expected = u'\\t' + SECURED_DEFAULT mock_objects.filter.return_value =",
"__init__(self): self.pattern = '^fake-regex-pattern/$' class MockRegexResolver: def __init__(self): self.pattern =",
"self._output.set_format('csv') self._output.process_application_data(app_name, app_type, view_list) self.assertEqual(expected, self._output._row) def test_cvs_format_process_application_data_without_type_to_string(self): app_name =",
"'django_roles_access:middleware_view_class', True) self.assertEqual(result, u'\\t' + DISABLED_DEFAULT) def test_with_middleware_with_view_access_object(self): expected =",
"get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result['roles-app-name']) class TestGetViewAnalyzeReport(UnitTestCase): def test_report_for_no_application_type(self): expected = u'\\t'",
"MockResolverDjango2() result = walk_site_url([MockPatternDjango2(), resolver]) self.assertEqual(result, expected_result) def test_param_list_with_pattern_and_nested_resolver_django_2(self): expected_result",
"u'\\t' + DISABLED_DEFAULT mock_objects.filter.return_value = mock_objects mock_objects.first.return_value = None result",
"created = Group.objects.get_or_create(name='test1') g2, created = Group.objects.get_or_create(name='test2') view_access = ViewAccess.objects.create(",
"True) self.assertEqual(result, expected) def test_with_middleware_with_view_access_object_public(self): expected = u'View access is",
"'^fake-nested-resolver/' class MockPattern: def __init__(self): self.regex = MockRegex() self.callback =",
"1) def test_console_format_write_correct_end_of_header( self ): expected = u'Finish gathering information.'",
"test_received_data_is_ordered_and_returned_by_application( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data",
"text') self.assertEqual(self.mock_stdout.write.call_count, 1) def test_console_format_use_SUCCESS_style_for_styling_output_of_vaa(self): self._output.write_view_access_analyzer(u'some text') self.mock_stdout.write.assert_called_once_with( self.mock_style.SUCCESS()) def",
"role-2' mock_view_access.type = 'br' role_1 = Mock() role_1.name = u'role-1'",
"expected_result = [ ('fake-regex-pattern/', 'fake-callback', 'fake-view-name', None), ('fake-resolver/fake-regex-pattern/', 'fake-callback', 'fake-namespace:fake-view-name',",
"'fake-app-name' ) ] result = walk_site_url([MockResolver(), MockResolverNested()]) self.assertEqual(result, expected_result) def",
"# ) # ] # resolver = MockResolverDjango2None2() # result",
"False) self.assertEqual(result, expected) class IntegratedTestViewAnalyzezr(TestCase): def test_with_middleware_SECURED_without_view_access_object(self): expected = u'\\t'",
"view_access_analyzer('fake-app-type', 'fake-callback', 'fake-view-name', 'fake-site-active') mock_objects.filter.assert_called_once_with(view='fake-view-name') def test_view_access_type_when_site_active_and_exists_view_access( self, mock_objects ):",
"self.namespace = 'fake-namespace' class MockResolverDjango2None: def __init__(self): self.pattern = '^fake-resolver/'",
"self.pattern = '^fake-resolver/' self.url_patterns = [MockResolverDjango2None()] self.app_name = 'fake-app-name' self.namespace",
"result = analyze_by_role(view_access) self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected = u'Roles",
"get_view_analyze_report('SECURED') self.assertEqual(result, expected) def test_report_for_application_type_PUBLIC(self): expected = u'\\t' + PUBLIC_DEFAULT",
"'fake-callback' self.name = 'fake-view-name' class MockResolver: def __init__(self): self.url_patterns =",
"self.assertEqual(result, expected) def test_detect_access_is_by_role_with_roles(self): expected = u'Roles with access: role-1,",
"view_access = ViewAccess.objects.create(view='any-name', type='br') result = analyze_by_role(view_access) self.assertEqual(result, expected) def",
"expected = u'\\t' + NOT_SECURED_DEFAULT result = get_view_analyze_report('NOT_SECURED') self.assertEqual(result, expected)",
"0 result = analyze_by_role(mock_view_access) self.assertEqual(result, expected) class IntegratedTestAnalyzeByRoleAccess(TestCase): def test_detect_access_is_by_role(self):",
"app_name = u'fake-app-name' app_type = None view_list = ['fake-view-list'] expected",
"url = '/fake-url/' expected = u'{},{}'.format(view_name, url) self._output.set_format('csv') self._output.process_view_data(view_name, url)",
"expected_result = ('nest1/nest2/view_by_role/', views.protected_view_by_role, 'nest1_namespace:nest2_namespace:view_' 'protected_by_role') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result,",
"self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] data =",
"= ('direct_access_view/', views.protected_view_by_role, 'direct_access_view') result = get_views_by_app(walk_site_url(self.url)) self.assertIn(expected_result, result[APP_NAME_FOR_NONE]) def",
"test_if_application_is_not_in_installed_apps_will_not_be_in_dict( self, mock_settings ): mock_settings.INSTALLED_APPS = ['fake-app-1', 'fake-app-2', None] result",
"test_console_format_use_WARNING_style_with_the_warning_in_vaa(self): self._output.write_view_access_analyzer('WARNING: fake report') self.mock_style.WARNING.assert_called_once_with( '\\t\\t' + 'WARNING: fake report')",
"self.mock_style.ERROR.called def test_console_format_use_ERROR_style_with_the_error_in_vaa(self): self._output.write_view_access_analyzer('ERROR: fake report') self.mock_style.ERROR.assert_called_once_with('\\t\\t' + 'ERROR: fake"
] |
[
"provide a valid group name.\") repeat = True elif Favs.exists(value,",
"0: # Single file name = view.file_name() if name !=",
"= 0 views = self.window.views() # If there is more",
"# Save if files were added Favs.save(True) if disk_omit_count: #",
"sublime.error_message(\"No favorites found! Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self,",
"group options self.window.show_quick_panel( self.group, self.group_answer ) def file_answer(self, value): if",
"self.group_prompt() if value == 1: # All files in window",
"file name = self.files[value - 1][1] else: # Remove global",
"= len(self.files) self.groups = [] self.num_groups = 0 # Show",
"if len(group_views) > 1: view_code = 2 self.file_prompt(view_code) else: #",
"No group; add file to favorites self.add(self.name) elif value ==",
"view_code = 1 # See if there is more than",
"# \"Replace Group\" self.show_groups(replace=True) def group_prompt(self): # Default options self.group",
"self.window.show_quick_panel( [\"Open Group\"] + self.files, lambda x: self.open_file(x, group=True) )",
"0: # Remove group Favs.remove_group(group_name) Favs.save(True) return else: # Remove",
"group_name=group_name) Favs.save(True) else: # Decend into group value -= self.num_files",
"exists.\") repeat = True else: # Add group Favs.add_group(value) self.add(self.name,",
"again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if",
"!= None: if active_group >= 0: self.window.set_view_index(view, active_group, count) count",
"if value >= 0: active_group = self.window.active_group() if value <",
"into group value -= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\",",
"else: sublime.error_message(\"No favorites found! Try adding some.\") def run(self): if",
"disk!\" if disk_omit_count == 1 else \"%d file(s) do not",
"group_answer(self, value): if value >= 0: if value == 0:",
"= 1 # See if there is more than one",
"of a specific group if self.window.num_groups() > 1: group, idx",
"Group\"] if Favs.group_count() > 0: # Options if groups already",
") else: sublime.error_message(\"No favorites found! Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand):",
"value >= 0: group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) if",
"\"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") def select_group(self, value,",
"!= None: if normpath(view.file_name()) == Refresh.dummy_file: # Close refresh file",
"sublime import sublime_plugin from os.path import join, exists, normpath from",
"if value == 0: # No group; add file to",
"v in views: name = v.file_name() if name != None:",
"path != None: if normpath(view.file_name()) == Refresh.dummy_file: # Close refresh",
"True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could not find a",
"self.group += [\"Add to Group\", \"Replace Group\"] # Present group",
"len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle again",
"if view != None: Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view),",
"to favorites self.add(self.name) elif value == 1: # Request new",
"in names: if exists(n): view = self.window.open_file(n) if view !=",
"in group names = [self.files[x][1] for x in range(0, self.num_files)]",
"== 2: # All files in layout group group, idx",
"= view.file_name() if name != None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand):",
"remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if Refresh.on: path =",
"value -= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files",
"group/global if not already added for n in names: if",
"% disk_omit_count sublime.error_message(message) def create_group(self, value): repeat = False if",
"for v in views: name = v.file_name() if name !=",
"value, replace=False): if value >= 0: group_name = self.groups[value][0].replace(\"Group: \",",
"Show panel if self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files",
"group files if self.num_files: self.window.show_quick_panel( [\"Remove Group\"] + self.files, lambda",
"self.window.views() # If there is more than one view open",
"view.file_name() if name != None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def",
"Favorite Files Licensed under MIT Copyright (c) 2012 <NAME> <<EMAIL>>",
"file list ensure they load in proper view index order",
"+ 1): # Open global file, file in group, or",
"if len(self.name) > 0: self.group_prompt() def file_prompt(self, view_code): # Add",
"them to group/global if not already added for n in",
"== 3: # \"Replace Group\" self.show_groups(replace=True) def group_prompt(self): # Default",
"None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False, group_name=None):",
"self.open_file ) else: sublime.error_message(\"No favorites found! Try adding some.\") class",
"# Present both files and groups for removal self.files =",
"if Refresh.on: Refresh.on = False refresh = False # Try",
"import Favorites Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh: dummy_file",
"= 0 # Show files in group if self.num_files: self.window.show_quick_panel(",
"value == 0: # No group; add file to favorites",
"# All files in layout group group, idx = self.window.get_view_index(view)",
"name = view.file_name() if name != None: self.name.append(name) self.group_prompt() class",
"# Open global file, file in group, or all fiels",
"return if value == 0: # Remove group Favs.remove_group(group_name) Favs.save(True)",
") else: sublime.error_message(\"No favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self,",
"files were added Favs.save(True) if disk_omit_count: # Alert that files",
"replace=False): if value >= 0: group_name = self.groups[value][0].replace(\"Group: \", \"\",",
"view != None: if active_group >= 0: self.window.set_view_index(view, active_group, count)",
"not exist on disk!\" % disk_omit_count sublime.error_message(message) def create_group(self, value):",
"(c) 2012 <NAME> <<EMAIL>> ''' import sublime import sublime_plugin from",
"Licensed under MIT Copyright (c) 2012 <NAME> <<EMAIL>> ''' import",
"group_name) def show_groups(self, replace=False): # Show availabe groups self.groups =",
"if len(self.name) > 0: self.group_prompt() if value == 2: #",
"layout group group, idx = self.window.get_view_index(view) views = self.window.views_in_group(group) if",
"join, exists, normpath from favorites import Favorites Favs = Favorites(join(sublime.packages_path(),",
"group_name == None: return if value == 0: # Remove",
"and save Favs.remove(name, group_name=group_name) Favs.save(True) else: # Decend into group",
"Show files in group if self.num_files: self.window.show_quick_panel( [\"Open Group\"] +",
"on_post_save(self, view): if Refresh.on: path = view.file_name() if path !=",
"too, maybe look into exclduing them if len(views) > 1:",
"0: active_group = self.window.active_group() if value < self.num_files or (group",
"Files to in Active Group to Favorites\") # Preset file",
"repeat = True else: # Add group Favs.add_group(value) self.add(self.name, value)",
"Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n, group_name=group_name) added += 1 else:",
"normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self):",
"on disk!\" % disk_omit_count sublime.error_message(message) def create_group(self, value): repeat =",
"# No group; add file to favorites self.add(self.name) elif value",
"Open file in group names.append(self.files[value - 1][1]) else: # Open",
"None: return if value == 0: # Remove group Favs.remove_group(group_name)",
"0 # Show group files if self.num_files: self.window.show_quick_panel( [\"Remove Group\"]",
"self.create_group, None, None ) v.run_command(\"select_all\") def select_group(self, value, replace=False): if",
"if view_code > 0: # Add all files in window",
"name sublime.error_message(\"Please provide a valid group name.\") repeat = True",
"self.file_answer ) def run(self): view = self.window.active_view() self.name = []",
"maybe look into exclduing them if len(views) > 1: view_code",
"in names: if not Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n, group_name=group_name)",
"if name != None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self,",
"name = None if group: if group_name == None: return",
"added = 0 # Iterate names and add them to",
"Present both files and groups for removal self.files = Favs.all_files()",
"value, group=False): if value >= 0: active_group = self.window.active_group() if",
"\"Replace Group\" selection Favs.add_group(group_name) # Add favorites self.add(self.name, group_name) def",
"toggle back to global first if not Favs.toggle_global(win_id): return #",
"if self.num_files: self.window.show_quick_panel( [\"Remove Group\"] + self.files, lambda x: self.remove(x,",
"favorites found! Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names,",
"self.window.get_view_index(view) views = self.window.views_in_group(group) if len(views) > 0: for v",
"group group, idx = self.window.get_view_index(view) views = self.window.views_in_group(group) if len(views)",
"# Remove file from global, file from group list, or",
"3: # \"Replace Group\" self.show_groups(replace=True) def group_prompt(self): # Default options",
"Group\" self.show_groups(replace=True) def group_prompt(self): # Default options self.group = [\"No",
"= self.window.views() # If there is more than one view",
"if value >= 0: # Remove file from global, file",
">= 0: # Remove file from global, file from group",
"or entire group if value < self.num_files or (group and",
"file from group list, or entire group if value <",
"len(self.groups) if self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files +",
"''' import sublime import sublime_plugin from os.path import join, exists,",
"self.num_files: self.window.show_quick_panel( [\"Remove Group\"] + self.files, lambda x: self.remove(x, group=True,",
"options, self.file_answer ) def run(self): view = self.window.active_view() self.name =",
"self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.open_file ) else:",
"run(self): if not Favs.load(win_id=self.window.id()): # Present both files and groups",
"# Options if groups already exit self.group += [\"Add to",
"# Try and toggle per project if refresh: view =",
"self.select_group(x, replace=replace) ) def group_answer(self, value): if value >= 0:",
"+= 1 else: # File does not exist on disk;",
"found! Try adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): self.files",
"group names.append(self.files[value - 1][1]) else: # Open global file names.append(self.files[value][1])",
"x: self.select_group(x, replace=replace) ) def group_answer(self, value): if value >=",
"group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) if replace: # Start",
"file_prompt(self, view_code): # Add current active file options = [\"Add",
"> 1: group, idx = self.window.get_view_index(view) group_views = self.window.views_in_group(group) if",
"Favs.toggle_global(win_id): return # Try and toggle per project if refresh:",
"on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean out",
"elif value == 1: # Request new group name v",
"False # Try and toggle back to global first if",
"group=True) ) else: sublime.error_message(\"No favorites found! Try adding some.\") def",
"file names.append(self.files[value][1]) # Iterate through file list ensure they load",
"n) else: # Decend into group value -= self.num_files self.files",
"if not Favs.toggle_global(win_id): return # Try and toggle per project",
"lambda x: self.remove(x, group=True, group_name=group_name) ) else: sublime.error_message(\"No favorites found!",
"group, idx = self.window.get_view_index(view) views = self.window.views_in_group(group) if len(views) >",
"If there is more than one view open allow saving",
"self.num_files + 1): # Open global file, file in group,",
"active_group, count) count += 1 else: sublime.error_message(\"The following file does",
"view open allow saving all views # TODO: Widget views",
"adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): self.files = Favs.all_files()",
"= Favs.all_files() self.num_files = len(self.files) self.groups = Favs.all_groups() self.num_groups =",
"group, idx = self.window.get_view_index(view) group_views = self.window.views_in_group(group) if len(group_views) >",
"self.window.show_quick_panel( self.files + self.groups, self.open_file ) else: sublime.error_message(\"No favorites found!",
"on disk!\" if disk_omit_count == 1 else \"%d file(s) do",
"self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x: self.select_group(x, replace=replace) )",
"exclduing them if len(views) > 1: view_code = 1 #",
"TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if Refresh.on: path = view.file_name() if",
"None: if value == 0: # Single file name =",
"!= None: view_code = 0 views = self.window.views() # If",
"self.add(self.name) elif value == 1: # Request new group name",
"# Preset file options self.window.show_quick_panel( options, self.file_answer ) def run(self):",
"be added message = \"1 file does not exist on",
"Only single file open, proceed without file options name =",
"x in range(0, self.num_files)] else: # Open file in group",
"disk_omit_count sublime.error_message(message) def create_group(self, value): repeat = False if value",
"options = [\"Add Current File to Favorites\"] if view_code >",
"all files in group names = [self.files[x][1] for x in",
"else: # File does not exist on disk; cannot add",
"= self.files[value][1] # Remove file and save Favs.remove(name, group_name=group_name) Favs.save(True)",
"self.create_group, None, None ) v.run_command(\"select_all\") elif value == 2: #",
"Present group options self.window.show_quick_panel( self.group, self.group_answer ) def file_answer(self, value):",
"if exists(n): Favs.set(n, group_name=group_name) added += 1 else: # File",
"0: view = self.window.active_view() if view != None: if value",
"else: sublime.error_message(\"The following file does not exist:\\n%s\" % n) else:",
"so allow saving of a specific group if self.window.num_groups() >",
"if value == 0: # Remove group Favs.remove_group(group_name) Favs.save(True) return",
"self.groups[value][0].replace(\"Group: \", \"\", 1) if replace: # Start with empty",
"names: if not Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n, group_name=group_name) added",
"in group names = [] if group: if value ==",
"Do not allow duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat =",
"Ask again if name was not sufficient v = self.window.show_input_panel(",
"if value < self.num_files or (group and value < self.num_files",
"added Favs.save(True) if disk_omit_count: # Alert that files could be",
"replace=False): # Show availabe groups self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups,",
"view_code > 0: # Add all files in window options.append(\"Add",
"normpath(view.file_name()) == Refresh.dummy_file: # Close refresh file if more than",
"sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could not find a project file!')",
"view): if Refresh.on: path = view.file_name() if path != None:",
"= Favs.all_groups() self.num_groups = len(self.groups) if self.num_files + self.num_groups >",
"self.save(view), 100) else: sublime.error_message('Could not find a project file!') else:",
"def run(self): if not Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files =",
"Active Group to Favorites\") # Preset file options self.window.show_quick_panel( options,",
"to global first if not Favs.toggle_global(win_id): return # Try and",
"if value >= 0: group_name = self.groups[value][0].replace(\"Group: \", \"\", 1)",
"> 0: # Options if groups already exit self.group +=",
"value == 3: # \"Replace Group\" self.show_groups(replace=True) def group_prompt(self): #",
"group=True): # Do not allow duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\")",
"if view_code > 1: # Add all files in layout",
"1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"),",
"len(self.name) > 0: self.group_prompt() if value == 2: # All",
"win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False): if value >=",
"is more than one group; if so allow saving of",
"file and save Favs.remove(name, group_name=group_name) Favs.save(True) else: # Decend into",
"All Files to in Active Group to Favorites\") # Preset",
"view = self.window.open_file(Refresh.dummy_file) if view != None: Refresh.on = True",
"exist:\\n%s\" % n) else: # Decend into group value -=",
"[\"Add to Group\", \"Replace Group\"] # Present group options self.window.show_quick_panel(",
"in layout group options.append(\"Add All Files to in Active Group",
"refresh: view = self.window.open_file(Refresh.dummy_file) if view != None: Refresh.on =",
"0: # Options if groups already exit self.group += [\"Add",
"len(group_views) > 1: view_code = 2 self.file_prompt(view_code) else: # Only",
"== 0: # No group; add file to favorites self.add(self.name)",
"else: sublime.error_message(\"No favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view):",
"# Add group Favs.add_group(value) self.add(self.name, value) if repeat: # Ask",
"None ) v.run_command(\"select_all\") elif value == 2: # \"Add to",
"added: # Save if files were added Favs.save(True) if disk_omit_count:",
"file(s) do not exist on disk!\" % disk_omit_count sublime.error_message(message) def",
"= True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could not find",
"# Open all files in group names = [self.files[x][1] for",
"ensure they load in proper view index order count =",
"options self.group = [\"No Group\", \"Create Group\"] if Favs.group_count() >",
"# Add favorites self.add(self.name, group_name) def show_groups(self, replace=False): # Show",
"# Add current active file options = [\"Add Current File",
"project if refresh: view = self.window.open_file(Refresh.dummy_file) if view != None:",
"views = self.window.views() if len(views) > 0: for v in",
"self.groups = Favs.all_groups() self.num_groups = len(self.groups) if self.num_files + self.num_groups",
"value < self.num_files + 1): # Open global file, file",
"up here too, maybe look into exclduing them if len(views)",
"<<EMAIL>> ''' import sublime import sublime_plugin from os.path import join,",
"self.num_files or (group and value < self.num_files + 1): name",
"replace=replace) ) def group_answer(self, value): if value >= 0: if",
">= 0: view = self.window.active_view() if view != None: if",
"+ 1): name = None if group: if group_name ==",
"Refresh.on: path = view.file_name() if path != None: if normpath(view.file_name())",
"\", \"\", 1)) self.num_files = len(self.files) self.groups = [] self.num_groups",
"favorites found! Try adding some.\") def run(self): if not Favs.load(win_id=self.window.id()):",
"toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view):",
"Favs.add_group(value) self.add(self.name, value) if repeat: # Ask again if name",
"file in group names.append(self.files[value - 1][1]) else: # Open global",
"> 0: for v in views: name = v.file_name() if",
"repeat = False if value == \"\": # Require an",
"a project file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a",
"more than one view open allow saving all views #",
"def run(self): # Clean out all dead links if not",
"# Close refresh file if more than one view is",
"disk!\" % disk_omit_count sublime.error_message(message) def create_group(self, value): repeat = False",
"and groups for removal self.files = Favs.all_files() self.num_files = len(self.files)",
"True else: # Add group Favs.add_group(value) self.add(self.name, value) if repeat:",
"if more than one view is open if len(view.window().views()) >",
"sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if Refresh.on: path",
"else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a project file!') else:",
"Show group files if self.num_files: self.window.show_quick_panel( [\"Remove Group\"] + self.files,",
"= self.window.views() if len(views) > 0: for v in views:",
"lambda x: self.select_group(x, replace=replace) ) def group_answer(self, value): if value",
"there is more than one group; if so allow saving",
"= self.window.open_file(Refresh.dummy_file) if view != None: Refresh.on = True self.window.focus_view(view)",
"files in group names = [self.files[x][1] for x in range(0,",
"def run(self): if not Favs.load(win_id=self.window.id()): # Present both files and",
"file, file in group, or all fiels in group names",
") def group_answer(self, value): if value >= 0: if value",
"Favs.load(win_id=self.window.id()): # Present both files and groups for removal self.files",
"else: sublime.error_message(\"No favorites found! Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def",
"1: # All files in window views = self.window.views() if",
"current active file options = [\"Add Current File to Favorites\"]",
"to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if Refresh.on: path",
"sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class",
"Options if groups already exit self.group += [\"Add to Group\",",
"\"%d file(s) do not exist on disk!\" % disk_omit_count sublime.error_message(message)",
"them if len(views) > 1: view_code = 1 # See",
") else: sublime.error_message(\"No favorites found! Try adding some.\") def run(self):",
"<gh_stars>1-10 ''' Favorite Files Licensed under MIT Copyright (c) 2012",
"-= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files =",
"= len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) # Show",
"= False if value == \"\": # Require an actual",
"than one view open allow saving all views # TODO:",
"Add all files in layout group options.append(\"Add All Files to",
"view_code): # Add current active file options = [\"Add Current",
"1 else \"%d file(s) do not exist on disk!\" %",
"= [\"No Group\", \"Create Group\"] if Favs.group_count() > 0: #",
"files could be added message = \"1 file does not",
"not allow duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat = True",
"fiels in group names = [] if group: if value",
"file in group, or all fiels in group names =",
"add disk_omit_count += 1 if added: # Save if files",
"not Favs.toggle_global(win_id): return # Try and toggle per project if",
"group_name=None): if value >= 0: # Remove file from global,",
"under MIT Copyright (c) 2012 <NAME> <<EMAIL>> ''' import sublime",
"if path != None: if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def",
"to Group\" self.show_groups() elif value == 3: # \"Replace Group\"",
"Group\", \"Replace Group\"] # Present group options self.window.show_quick_panel( self.group, self.group_answer",
"\"Add to Group\" self.show_groups() elif value == 3: # \"Replace",
"0: self.window.show_quick_panel( self.files + self.groups, self.remove ) else: sublime.error_message(\"No favorites",
"out all dead links if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True,",
"for n in names: if exists(n): view = self.window.open_file(n) if",
"See if there is more than one group; if so",
"was not sufficient v = self.window.show_input_panel( \"Create Group: \", \"New",
"files in layout group options.append(\"Add All Files to in Active",
"Group: \", \"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") elif",
"or all fiels in group names = [] if group:",
"elif Favs.exists(value, group=True): # Do not allow duplicates sublime.error_message(\"Group \\\"%s\\\"",
"= False refresh = False # Try and toggle back",
"+ self.groups, self.remove ) else: sublime.error_message(\"No favorites to remove!\") class",
"# Default options self.group = [\"No Group\", \"Create Group\"] if",
"add them to group/global if not already added for n",
"else: # Decend into group value -= self.num_files group_name =",
"find a project file!') else: Favs.open(win_id=self.window.id()) def is_enabled(self): return sublime.load_settings(\"favorite_files.sublime-settings\").get(\"enable_per_projects\",",
"len(self.files) self.groups = [] self.num_groups = 0 # Show group",
"count) count += 1 else: sublime.error_message(\"The following file does not",
"idx = self.window.get_view_index(view) views = self.window.views_in_group(group) if len(views) > 0:",
"normpath from favorites import Favorites Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json'))",
"class Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on = False",
"else: # Add group Favs.add_group(value) self.add(self.name, value) if repeat: #",
"self.name.append(name) if len(self.name) > 0: self.group_prompt() def file_prompt(self, view_code): #",
"in proper view index order count = 0 for n",
"if self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups,",
"len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) if self.num_files +",
"group Favs.add_group(value) self.add(self.name, value) if repeat: # Ask again if",
"availabe groups self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x: self.select_group(x,",
"self.window.views_in_group(group) if len(views) > 0: for v in views: name",
"count += 1 else: sublime.error_message(\"The following file does not exist:\\n%s\"",
"def on_post_save(self, view): if Refresh.on: path = view.file_name() if path",
"replace: # Start with empty group for \"Replace Group\" selection",
"!= None: self.name.append(name) if len(self.name) > 0: self.group_prompt() def file_prompt(self,",
") def run(self): view = self.window.active_view() self.name = [] if",
"self.group_prompt() def file_prompt(self, view_code): # Add current active file options",
"views: name = v.file_name() if name != None: self.name.append(name) if",
"self.files[value][1] # Remove file and save Favs.remove(name, group_name=group_name) Favs.save(True) else:",
"Group\"] + self.files, lambda x: self.open_file(x, group=True) ) else: sublime.error_message(\"No",
"len(self.files) self.groups = [] self.num_groups = 0 # Show files",
"added for n in names: if not Favs.exists(n, group_name=group_name): if",
"False if value == \"\": # Require an actual name",
"Add group Favs.add_group(value) self.add(self.name, value) if repeat: # Ask again",
"self.name.append(name) if len(self.name) > 0: self.group_prompt() if value == 2:",
"Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups = [] self.num_groups = 0",
"self.window.views() if len(views) > 0: for v in views: name",
"project file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a project",
"0: self.window.set_view_index(view, active_group, count) count += 1 else: sublime.error_message(\"The following",
"= self.window.id() if Refresh.on: Refresh.on = False refresh = False",
"an actual name sublime.error_message(\"Please provide a valid group name.\") repeat",
"Group\" self.show_groups() elif value == 3: # \"Replace Group\" self.show_groups(replace=True)",
"for x in range(0, self.num_files)] else: # Open file in",
"to Group\", \"Replace Group\"] # Present group options self.window.show_quick_panel( self.group,",
"= [] self.num_groups = 0 # Show group files if",
"Refresh.on = False refresh = False # Try and toggle",
"None: Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could",
"groups self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x: self.select_group(x, replace=replace)",
"None, None ) v.run_command(\"select_all\") elif value == 2: # \"Add",
"Favorites\") if view_code > 1: # Add all files in",
"options self.window.show_quick_panel( options, self.file_answer ) def run(self): view = self.window.active_view()",
"view_code = 2 self.file_prompt(view_code) else: # Only single file open,",
"= [] if group: if value == 0: # Open",
"# Iterate through file list ensure they load in proper",
"Open global file, file in group, or all fiels in",
"\"\", 1) if replace: # Start with empty group for",
"self.remove ) else: sublime.error_message(\"No favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def",
"None: self.name.append(name) if len(self.name) > 0: self.group_prompt() if value ==",
"else: # Open global file names.append(self.files[value][1]) # Iterate through file",
"exist on disk!\" % disk_omit_count sublime.error_message(message) def create_group(self, value): repeat",
"File to Favorites\"] if view_code > 0: # Add all",
"# Add all files in window options.append(\"Add All Files to",
"!= None: self.name.append(name) if len(self.name) > 0: self.group_prompt() if value",
"a valid group name.\") repeat = True elif Favs.exists(value, group=True):",
"Require an actual name sublime.error_message(\"Please provide a valid group name.\")",
"1][1]) else: # Open global file names.append(self.files[value][1]) # Iterate through",
"= True else: # Add group Favs.add_group(value) self.add(self.name, value) if",
"class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False, group_name=None): if value >=",
"(group and value < self.num_files + 1): name = None",
"than one view is open if len(view.window().views()) > 1: sublime.set_timeout(lambda:",
"= False # Try and toggle back to global first",
"global first if not Favs.toggle_global(win_id): return # Try and toggle",
"not find a project file!') else: Favs.open(win_id=self.window.id()) def is_enabled(self): return",
"self.files = Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups = [] self.num_groups",
"sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000)",
"\", \"\", 1) if replace: # Start with empty group",
"self.add(self.name, group_name) def show_groups(self, replace=False): # Show availabe groups self.groups",
"\"Create Group: \", \"New Group\", self.create_group, None, None ) v.run_command(\"select_all\")",
"# Open file in group names.append(self.files[value - 1][1]) else: #",
"options.append(\"Add All Files to Favorites\") if view_code > 1: #",
"+ self.files, lambda x: self.open_file(x, group=True) ) else: sublime.error_message(\"No favorites",
"name != None: self.name.append(name) if len(self.name) > 0: self.group_prompt() if",
"Favs.all_files() self.num_files = len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups)",
"already added for n in names: if not Favs.exists(n, group_name=group_name):",
"already exit self.group += [\"Add to Group\", \"Replace Group\"] #",
"'User', 'favorite_files_list.json')) class Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on",
"idx = self.window.get_view_index(view) group_views = self.window.views_in_group(group) if len(group_views) > 1:",
"group: if group_name == None: return if value == 0:",
"for removal self.files = Favs.all_files() self.num_files = len(self.files) self.groups =",
"and add them to group/global if not already added for",
"selection Favs.add_group(group_name) # Add favorites self.add(self.name, group_name) def show_groups(self, replace=False):",
"if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def",
"if group: if group_name == None: return if value ==",
"= view.file_name() if name != None: self.name.append(name) self.group_prompt() if value",
"# Add all files in layout group options.append(\"Add All Files",
"name = self.files[value][1] # Remove file and save Favs.remove(name, group_name=group_name)",
"self.groups = Favs.all_groups() self.num_groups = len(self.groups) # Show panel if",
"first if not Favs.toggle_global(win_id): return # Try and toggle per",
"False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean out all dead",
"self.group, self.group_answer ) def file_answer(self, value): if value >= 0:",
"name != None: self.name.append(name) self.group_prompt() if value == 1: #",
"self.files, lambda x: self.remove(x, group=True, group_name=group_name) ) else: sublime.error_message(\"No favorites",
"= self.window.active_group() if value < self.num_files or (group and value",
"self.window.show_quick_panel( self.files + self.groups, self.remove ) else: sublime.error_message(\"No favorites to",
"add(self, names, group_name=None): disk_omit_count = 0 added = 0 #",
"Group: \", \"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") def",
"if replace: # Start with empty group for \"Replace Group\"",
"Iterate names and add them to group/global if not already",
"if normpath(view.file_name()) == Refresh.dummy_file: # Close refresh file if more",
"if repeat: # Ask again if name was not sufficient",
"self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files = len(self.files)",
"view = self.window.active_view() self.name = [] if view != None:",
"!= None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False,",
"if len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle",
"all files in window options.append(\"Add All Files to Favorites\") if",
"# Remove group Favs.remove_group(group_name) Favs.save(True) return else: # Remove group",
"\"\", 1)) self.num_files = len(self.files) self.groups = [] self.num_groups =",
"sublime.error_message(message) def create_group(self, value): repeat = False if value ==",
"self.window.open_file(n) if view != None: if active_group >= 0: self.window.set_view_index(view,",
"Add all files in window options.append(\"Add All Files to Favorites\")",
"> 0: self.group_prompt() if value == 2: # All files",
"self.file_prompt(view_code) else: # Only single file open, proceed without file",
"+= [\"Add to Group\", \"Replace Group\"] # Present group options",
"not exist:\\n%s\" % n) else: # Decend into group value",
"if Favs.group_count() > 0: # Options if groups already exit",
"value < self.num_files or (group and value < self.num_files +",
"active file options = [\"Add Current File to Favorites\"] if",
"= self.window.active_view() self.name = [] if view != None: view_code",
"return # Try and toggle per project if refresh: view",
"value == 0: # Single file name = view.file_name() if",
"+= 1 else: sublime.error_message(\"The following file does not exist:\\n%s\" %",
"> 1: view_code = 2 self.file_prompt(view_code) else: # Only single",
"self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files = len(self.files) self.groups",
"that files could be added message = \"1 file does",
"0: # Remove file from global, file from group list,",
"list, or entire group if value < self.num_files or (group",
"exists(n): view = self.window.open_file(n) if view != None: if active_group",
"# Do not allow duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat",
"Favorites\") # Preset file options self.window.show_quick_panel( options, self.file_answer ) def",
"self.num_files + 1): name = None if group: if group_name",
"\"\": # Require an actual name sublime.error_message(\"Please provide a valid",
"group_name=group_name) ) else: sublime.error_message(\"No favorites found! Try adding some.\") def",
"% n) else: # Decend into group value -= self.num_files",
"if path != None: if normpath(view.file_name()) == Refresh.dummy_file: # Close",
"view.file_name() if path != None: if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save')",
"if refresh: view = self.window.open_file(Refresh.dummy_file) if view != None: Refresh.on",
"group names = [] if group: if value == 0:",
"win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False):",
"names: if exists(n): view = self.window.open_file(n) if view != None:",
"Favorites Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh: dummy_file =",
"if not Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files = len(self.files) self.groups",
"Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None): disk_omit_count",
"Group\" selection Favs.add_group(group_name) # Add favorites self.add(self.name, group_name) def show_groups(self,",
"== 1: # All files in window views = self.window.views()",
"Files Licensed under MIT Copyright (c) 2012 <NAME> <<EMAIL>> '''",
"def file_prompt(self, view_code): # Add current active file options =",
"# If there is more than one view open allow",
"from os.path import join, exists, normpath from favorites import Favorites",
"> 1: view_code = 1 # See if there is",
"self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.remove",
"= Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups = [] self.num_groups =",
"Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on = False class",
"sublime.error_message(\"No favorites found! Try adding some.\") def run(self): if not",
"Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a project file!') else: Favs.open(win_id=self.window.id()) def",
"group_name=group_name) added += 1 else: # File does not exist",
"class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False): if value >= 0:",
"in Active Group to Favorites\") # Preset file options self.window.show_quick_panel(",
"sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if Refresh.on:",
"self.num_files)] else: # Open file in group names.append(self.files[value - 1][1])",
"does not exist on disk!\" if disk_omit_count == 1 else",
"group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) self.files = Favs.all_files(group_name=group_name) self.num_files",
"to Favorites\") # Preset file options self.window.show_quick_panel( options, self.file_answer )",
"removal self.files = Favs.all_files() self.num_files = len(self.files) self.groups = Favs.all_groups()",
"value == 0: # Remove group Favs.remove_group(group_name) Favs.save(True) return else:",
"def create_group(self, value): repeat = False if value == \"\":",
"file if more than one view is open if len(view.window().views())",
"Favs.save(True) if disk_omit_count: # Alert that files could be added",
"lambda x: self.open_file(x, group=True) ) else: sublime.error_message(\"No favorites found! Try",
"self.name = [] if view != None: view_code = 0",
"message = \"1 file does not exist on disk!\" if",
"if files were added Favs.save(True) if disk_omit_count: # Alert that",
"= 0 for n in names: if exists(n): view =",
"disk_omit_count == 1 else \"%d file(s) do not exist on",
"# Decend into group value -= self.num_files group_name = self.groups[value][0].replace(\"Group:",
"Widget views probably show up here too, maybe look into",
"else: # Remove group file name = self.files[value - 1][1]",
"Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could not",
"cannot add disk_omit_count += 1 if added: # Save if",
"some.\") def run(self): if not Favs.load(win_id=self.window.id()): # Present both files",
"\\\"%s\\\" already exists.\") repeat = True else: # Add group",
"<NAME> <<EMAIL>> ''' import sublime import sublime_plugin from os.path import",
"if name != None: self.name.append(name) if len(self.name) > 0: self.group_prompt()",
"[] if view != None: view_code = 0 views =",
"= [\"Add Current File to Favorites\"] if view_code > 0:",
"name = self.files[value - 1][1] else: # Remove global file",
"= self.window.views_in_group(group) if len(views) > 0: for v in views:",
"exists, normpath from favorites import Favorites Favs = Favorites(join(sublime.packages_path(), 'User',",
"\", \"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") def select_group(self,",
"Decend into group value -= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \",",
"per project if refresh: view = self.window.open_file(Refresh.dummy_file) if view !=",
"active_group = self.window.active_group() if value < self.num_files or (group and",
"value >= 0: if value == 0: # No group;",
"window options.append(\"Add All Files to Favorites\") if view_code > 1:",
"self.num_files or (group and value < self.num_files + 1): #",
"file options = [\"Add Current File to Favorites\"] if view_code",
"len(views) > 1: view_code = 1 # See if there",
"allow saving of a specific group if self.window.num_groups() > 1:",
"= self.files[value - 1][1] else: # Remove global file name",
"Favs.set(n, group_name=group_name) added += 1 else: # File does not",
"None: if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def run(self): refresh =",
"to group/global if not already added for n in names:",
"Decend into group value -= self.num_files group_name = self.groups[value][0].replace(\"Group: \",",
"dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand):",
"[\"No Group\", \"Create Group\"] if Favs.group_count() > 0: # Options",
"= view.file_name() if path != None: if normpath(view.file_name()) == Refresh.dummy_file:",
"== 1: # Request new group name v = self.window.show_input_panel(",
"Favs.save(True) return else: # Remove group file name = self.files[value",
"def run(self): view = self.window.active_view() self.name = [] if view",
"view_code > 1: # Add all files in layout group",
"= None if group: if group_name == None: return if",
"= len(self.groups) # Show panel if self.num_files + self.num_groups >",
"view = self.window.active_view() if view != None: if value ==",
"if len(views) > 0: for v in views: name =",
"1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if Refresh.on: path =",
"MIT Copyright (c) 2012 <NAME> <<EMAIL>> ''' import sublime import",
"= self.groups[value][0].replace(\"Group: \", \"\", 1) self.files = Favs.all_files(group_name=group_name) self.num_files =",
"'favorite_files_list.json')) class Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on =",
"self.groups, self.remove ) else: sublime.error_message(\"No favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener):",
"if active_group >= 0: self.window.set_view_index(view, active_group, count) count += 1",
"index order count = 0 for n in names: if",
"= Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files = len(self.files) self.groups =",
">= 0: active_group = self.window.active_group() if value < self.num_files or",
"-= self.num_files group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) self.files =",
"class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean out all dead links",
"view != None: if value == 0: # Single file",
"import sublime_plugin from os.path import join, exists, normpath from favorites",
"all files in layout group options.append(\"Add All Files to in",
"more than one group; if so allow saving of a",
"n in names: if not Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n,",
"if not Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n, group_name=group_name) added +=",
"already exists.\") repeat = True else: # Add group Favs.add_group(value)",
"# Decend into group value -= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group:",
"all views # TODO: Widget views probably show up here",
"2012 <NAME> <<EMAIL>> ''' import sublime import sublime_plugin from os.path",
"1 if added: # Save if files were added Favs.save(True)",
"[\"Open Group\"] + self.files, lambda x: self.open_file(x, group=True) ) else:",
"file_answer(self, value): if value >= 0: view = self.window.active_view() if",
"if view != None: if active_group >= 0: self.window.set_view_index(view, active_group,",
"All files in window views = self.window.views() if len(views) >",
"Try adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): self.files =",
"Favs.all_groups() self.num_groups = len(self.groups) if self.num_files + self.num_groups > 0:",
"v.file_name() if name != None: self.name.append(name) if len(self.name) > 0:",
"None if group: if group_name == None: return if value",
"Preset file options self.window.show_quick_panel( options, self.file_answer ) def run(self): view",
"All Files to Favorites\") if view_code > 1: # Add",
"group options.append(\"Add All Files to in Active Group to Favorites\")",
"# Try and toggle back to global first if not",
"and value < self.num_files + 1): name = None if",
"favorites import Favorites Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh:",
"# See if there is more than one group; if",
"value == \"\": # Require an actual name sublime.error_message(\"Please provide",
"valid group name.\") repeat = True elif Favs.exists(value, group=True): #",
"+= 1 if added: # Save if files were added",
"self.add(self.name, value) if repeat: # Ask again if name was",
"self.window.active_view() if view != None: if value == 0: #",
"file options self.window.show_quick_panel( options, self.file_answer ) def run(self): view =",
"def remove(self, value, group=False, group_name=None): if value >= 0: #",
"= 0 # Show group files if self.num_files: self.window.show_quick_panel( [\"Remove",
"more than one view is open if len(view.window().views()) > 1:",
"0: if value == 0: # No group; add file",
"= self.window.active_view() if view != None: if value == 0:",
"# Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def",
"from group list, or entire group if value < self.num_files",
"some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None): disk_omit_count = 0",
"Iterate through file list ensure they load in proper view",
"== 1 else \"%d file(s) do not exist on disk!\"",
"file name = self.files[value][1] # Remove file and save Favs.remove(name,",
"Current File to Favorites\"] if view_code > 0: # Add",
"group Favs.remove_group(group_name) Favs.save(True) return else: # Remove group file name",
"Favs.all_groups() self.num_groups = len(self.groups) # Show panel if self.num_files +",
"class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None): disk_omit_count = 0 added",
"Refresh.dummy_file: view.run_command('save') def run(self): refresh = True win_id = self.window.id()",
"0 # Iterate names and add them to group/global if",
"group_prompt(self): # Default options self.group = [\"No Group\", \"Create Group\"]",
"self.window.get_view_index(view) group_views = self.window.views_in_group(group) if len(group_views) > 1: view_code =",
"look into exclduing them if len(views) > 1: view_code =",
"sublime.error_message(\"No favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if",
"found! Try adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): #",
"= False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean out all",
"self.files[value - 1][1] else: # Remove global file name =",
"files and groups for removal self.files = Favs.all_files() self.num_files =",
"if value >= 0: view = self.window.active_view() if view !=",
"if group: if value == 0: # Open all files",
"load in proper view index order count = 0 for",
"disk_omit_count: # Alert that files could be added message =",
"view != None: view_code = 0 views = self.window.views() #",
"'refresh.txt')) on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean",
"self.files + self.groups, self.open_file ) else: sublime.error_message(\"No favorites found! Try",
"self.group_answer ) def file_answer(self, value): if value >= 0: view",
"in window views = self.window.views() if len(views) > 0: for",
"group if self.window.num_groups() > 1: group, idx = self.window.get_view_index(view) group_views",
"value): if value >= 0: view = self.window.active_view() if view",
"file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a project file!')",
"True elif Favs.exists(value, group=True): # Do not allow duplicates sublime.error_message(\"Group",
"self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False, group_name=None): if",
"both files and groups for removal self.files = Favs.all_files() self.num_files",
"to in Active Group to Favorites\") # Preset file options",
"< self.num_files + 1): # Open global file, file in",
"self.window.views_in_group(group) if len(group_views) > 1: view_code = 2 self.file_prompt(view_code) else:",
"Remove group Favs.remove_group(group_name) Favs.save(True) return else: # Remove group file",
"sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat = True else: # Add",
"self.num_files = len(self.files) self.groups = [] self.num_groups = 0 #",
"== 0: # Open all files in group names =",
"''' Favorite Files Licensed under MIT Copyright (c) 2012 <NAME>",
"not exist on disk!\" if disk_omit_count == 1 else \"%d",
"one view open allow saving all views # TODO: Widget",
"in group if self.num_files: self.window.show_quick_panel( [\"Open Group\"] + self.files, lambda",
"for n in names: if not Favs.exists(n, group_name=group_name): if exists(n):",
"views probably show up here too, maybe look into exclduing",
"group=True, group_name=group_name) ) else: sublime.error_message(\"No favorites found! Try adding some.\")",
"0 # Show files in group if self.num_files: self.window.show_quick_panel( [\"Open",
"def save(self, view): if Refresh.on: path = view.file_name() if path",
"CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): # Clean out all dead links if",
"2: # All files in layout group group, idx =",
"value >= 0: # Remove file from global, file from",
"len(self.groups) # Show panel if self.num_files + self.num_groups > 0:",
"adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None): disk_omit_count =",
"exit self.group += [\"Add to Group\", \"Replace Group\"] # Present",
"1: # Add all files in layout group options.append(\"Add All",
"x: self.open_file(x, group=True) ) else: sublime.error_message(\"No favorites found! Try adding",
"# All files in window views = self.window.views() if len(views)",
"sublime.error_message('Could not find a project file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could",
"len(views) > 0: for v in views: name = v.file_name()",
"self.window.show_input_panel( \"Create Group: \", \"New Group\", self.create_group, None, None )",
"not sufficient v = self.window.show_input_panel( \"Create Group: \", \"New Group\",",
"1 # See if there is more than one group;",
"Favs.save(True) else: # Decend into group value -= self.num_files group_name",
"self.groups, lambda x: self.select_group(x, replace=replace) ) def group_answer(self, value): if",
"= v.file_name() if name != None: self.name.append(name) if len(self.name) >",
"> 0: self.window.show_quick_panel( self.files + self.groups, self.remove ) else: sublime.error_message(\"No",
"dead links if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class",
"0: self.window.show_quick_panel( self.files + self.groups, self.open_file ) else: sublime.error_message(\"No favorites",
"global, file from group list, or entire group if value",
"\"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") elif value ==",
"0 views = self.window.views() # If there is more than",
"100) # Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand):",
"Files to Favorites\") if view_code > 1: # Add all",
"run(self): refresh = True win_id = self.window.id() if Refresh.on: Refresh.on",
"1: # Request new group name v = self.window.show_input_panel( \"Create",
"find a project file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find",
"duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat = True else: #",
"Attempt toggle again sublime.set_timeout(lambda: sublime.active_window().run_command(\"toggle_per_project_favorites\"), 1000) class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self,",
"Remove group file name = self.files[value - 1][1] else: #",
"value < self.num_files + 1): name = None if group:",
"else: sublime.error_message('Could not find a project file!') else: if Favs.toggle_per_projects(win_id):",
"file does not exist:\\n%s\" % n) else: # Decend into",
"layout group options.append(\"Add All Files to in Active Group to",
"value == 1: # All files in window views =",
"not exist on disk; cannot add disk_omit_count += 1 if",
"group name v = self.window.show_input_panel( \"Create Group: \", \"New Group\",",
"files in layout group group, idx = self.window.get_view_index(view) views =",
"show up here too, maybe look into exclduing them if",
"saving of a specific group if self.window.num_groups() > 1: group,",
"for \"Replace Group\" selection Favs.add_group(group_name) # Add favorites self.add(self.name, group_name)",
"v.run_command(\"select_all\") def select_group(self, value, replace=False): if value >= 0: group_name",
"self.open_file(x, group=True) ) else: sublime.error_message(\"No favorites found! Try adding some.\")",
"0: # Add all files in window options.append(\"Add All Files",
"[] self.num_groups = 0 # Show group files if self.num_files:",
"window views = self.window.views() if len(views) > 0: for v",
">= 0: if value == 0: # No group; add",
"from global, file from group list, or entire group if",
"Clean out all dead links if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True,",
"show_groups(self, replace=False): # Show availabe groups self.groups = Favs.all_groups() self.window.show_quick_panel(",
"all dead links if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id())",
"SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False): if value >= 0: active_group",
"None, None ) v.run_command(\"select_all\") def select_group(self, value, replace=False): if value",
"100) else: sublime.error_message('Could not find a project file!') else: if",
"# Require an actual name sublime.error_message(\"Please provide a valid group",
"None: if active_group >= 0: self.window.set_view_index(view, active_group, count) count +=",
"empty group for \"Replace Group\" selection Favs.add_group(group_name) # Add favorites",
"AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None): disk_omit_count = 0 added =",
"self.files, lambda x: self.open_file(x, group=True) ) else: sublime.error_message(\"No favorites found!",
"value == 2: # All files in layout group group,",
"not find a project file!') else: if Favs.toggle_per_projects(win_id): sublime.error_message('Could not",
"Show availabe groups self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x:",
"import sublime import sublime_plugin from os.path import join, exists, normpath",
"options self.window.show_quick_panel( self.group, self.group_answer ) def file_answer(self, value): if value",
"file to favorites self.add(self.name) elif value == 1: # Request",
"here too, maybe look into exclduing them if len(views) >",
"in views: name = v.file_name() if name != None: self.name.append(name)",
"False refresh = False # Try and toggle back to",
"1][1] else: # Remove global file name = self.files[value][1] #",
"name != None: self.name.append(name) self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value,",
"name was not sufficient v = self.window.show_input_panel( \"Create Group: \",",
"> 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt toggle again sublime.set_timeout(lambda:",
"self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else: sublime.error_message('Could not find a project",
"else: # Open file in group names.append(self.files[value - 1][1]) else:",
"not Favs.exists(n, group_name=group_name): if exists(n): Favs.set(n, group_name=group_name) added += 1",
"File does not exist on disk; cannot add disk_omit_count +=",
"added message = \"1 file does not exist on disk!\"",
"(group and value < self.num_files + 1): # Open global",
"def select_group(self, value, replace=False): if value >= 0: group_name =",
"# Show files in group if self.num_files: self.window.show_quick_panel( [\"Open Group\"]",
"# Remove file and save Favs.remove(name, group_name=group_name) Favs.save(True) else: #",
"not already added for n in names: if not Favs.exists(n,",
"exists(n): Favs.set(n, group_name=group_name) added += 1 else: # File does",
"else \"%d file(s) do not exist on disk!\" % disk_omit_count",
"\"Create Group\"] if Favs.group_count() > 0: # Options if groups",
"= Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles',",
"self.window.show_quick_panel( options, self.file_answer ) def run(self): view = self.window.active_view() self.name",
"one group; if so allow saving of a specific group",
"exist on disk!\" if disk_omit_count == 1 else \"%d file(s)",
"saving all views # TODO: Widget views probably show up",
"open_file(self, value, group=False): if value >= 0: active_group = self.window.active_group()",
"self.show_groups(replace=True) def group_prompt(self): # Default options self.group = [\"No Group\",",
"if value == 0: # Single file name = view.file_name()",
"value >= 0: view = self.window.active_view() if view != None:",
"in range(0, self.num_files)] else: # Open file in group names.append(self.files[value",
"Group\", self.create_group, None, None ) v.run_command(\"select_all\") elif value == 2:",
"0 added = 0 # Iterate names and add them",
"self.show_groups() elif value == 3: # \"Replace Group\" self.show_groups(replace=True) def",
"= self.window.open_file(n) if view != None: if active_group >= 0:",
"= True elif Favs.exists(value, group=True): # Do not allow duplicates",
"if Favs.toggle_per_projects(win_id): sublime.error_message('Could not find a project file!') else: Favs.open(win_id=self.window.id())",
"sublime_plugin from os.path import join, exists, normpath from favorites import",
"self.num_files: self.window.show_quick_panel( [\"Open Group\"] + self.files, lambda x: self.open_file(x, group=True)",
"= self.window.show_input_panel( \"Create Group: \", \"New Group\", self.create_group, None, None",
"# Show panel if self.num_files + self.num_groups > 0: self.window.show_quick_panel(",
"view != None: Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100)",
"list ensure they load in proper view index order count",
"they load in proper view index order count = 0",
"self.window.active_view() self.name = [] if view != None: view_code =",
"RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False, group_name=None): if value >= 0:",
"if group_name == None: return if value == 0: #",
"value -= self.num_files group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) self.files",
"Try adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): # Present",
"os.path import join, exists, normpath from favorites import Favorites Favs",
"or (group and value < self.num_files + 1): # Open",
"= \"1 file does not exist on disk!\" if disk_omit_count",
"if len(views) > 1: view_code = 1 # See if",
"group value -= self.num_files self.files = Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1))",
"else: # Remove global file name = self.files[value][1] # Remove",
"run(self): view = self.window.active_view() self.name = [] if view !=",
"if not Favs.load(win_id=self.window.id()): # Present both files and groups for",
"None ) v.run_command(\"select_all\") def select_group(self, value, replace=False): if value >=",
"value): if value >= 0: if value == 0: #",
"options name = view.file_name() if name != None: self.name.append(name) self.group_prompt()",
"< self.num_files or (group and value < self.num_files + 1):",
"normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def run(self): refresh = True win_id",
"v = self.window.show_input_panel( \"Create Group: \", \"New Group\", self.create_group, None,",
"def open_file(self, value, group=False): if value >= 0: active_group =",
"disk_omit_count = 0 added = 0 # Iterate names and",
"global file, file in group, or all fiels in group",
"self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.open_file",
"Alert that files could be added message = \"1 file",
"Refresh.dummy_file: # Close refresh file if more than one view",
"FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if Refresh.on: path = view.file_name() if",
"group names = [self.files[x][1] for x in range(0, self.num_files)] else:",
"self.window.show_quick_panel( self.group, self.group_answer ) def file_answer(self, value): if value >=",
"is open if len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) #",
"path = view.file_name() if path != None: if normpath(view.file_name()) ==",
"back to global first if not Favs.toggle_global(win_id): return # Try",
"exist on disk; cannot add disk_omit_count += 1 if added:",
"new group name v = self.window.show_input_panel( \"Create Group: \", \"New",
"elif value == 2: # \"Add to Group\" self.show_groups() elif",
"= len(self.groups) if self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files",
"= [self.files[x][1] for x in range(0, self.num_files)] else: # Open",
"Remove file and save Favs.remove(name, group_name=group_name) Favs.save(True) else: # Decend",
"refresh = False # Try and toggle back to global",
"sublime.error_message('Could not find a project file!') else: Favs.open(win_id=self.window.id()) def is_enabled(self):",
"Refresh.on: Refresh.on = False refresh = False # Try and",
"one view is open if len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"),",
"self.remove(x, group=True, group_name=group_name) ) else: sublime.error_message(\"No favorites found! Try adding",
"self.files = Favs.all_files() self.num_files = len(self.files) self.groups = Favs.all_groups() self.num_groups",
"# Show group files if self.num_files: self.window.show_quick_panel( [\"Remove Group\"] +",
"links if not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand):",
"in group, or all fiels in group names = []",
"> 0: self.window.show_quick_panel( self.files + self.groups, self.open_file ) else: sublime.error_message(\"No",
"0 for n in names: if exists(n): view = self.window.open_file(n)",
"group name.\") repeat = True elif Favs.exists(value, group=True): # Do",
"Add favorites self.add(self.name, group_name) def show_groups(self, replace=False): # Show availabe",
"remove(self, value, group=False, group_name=None): if value >= 0: # Remove",
"# Remove group file name = self.files[value - 1][1] else:",
"== Refresh.dummy_file: # Close refresh file if more than one",
"self.name.append(name) self.group_prompt() if value == 1: # All files in",
") def file_answer(self, value): if value >= 0: view =",
"Default options self.group = [\"No Group\", \"Create Group\"] if Favs.group_count()",
"# Open global file names.append(self.files[value][1]) # Iterate through file list",
"clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False): if value",
"open allow saving all views # TODO: Widget views probably",
"Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh: dummy_file = normpath(join(sublime.packages_path(),",
"v.run_command(\"select_all\") elif value == 2: # \"Add to Group\" self.show_groups()",
"> 0: # Add all files in window options.append(\"Add All",
"# Clean out all dead links if not Favs.load(clean=True, win_id=self.window.id()):",
"open if len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100) # Attempt",
"None: self.name.append(name) self.group_prompt() if value == 1: # All files",
"add file to favorites self.add(self.name) elif value == 1: #",
"None: self.name.append(name) if len(self.name) > 0: self.group_prompt() def file_prompt(self, view_code):",
"Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files = len(self.files) self.groups = Favs.all_groups()",
"does not exist on disk; cannot add disk_omit_count += 1",
"> 1: # Add all files in layout group options.append(\"Add",
"panel if self.num_files + self.num_groups > 0: self.window.show_quick_panel( self.files +",
"class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if Refresh.on: path = view.file_name()",
"1) self.files = Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups = []",
"self.group_prompt() class RemoveFavoriteFileCommand(sublime_plugin.WindowCommand): def remove(self, value, group=False, group_name=None): if value",
"# TODO: Widget views probably show up here too, maybe",
"files in window options.append(\"Add All Files to Favorites\") if view_code",
"1): name = None if group: if group_name == None:",
">= 0: group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) if replace:",
"not Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files = len(self.files) self.groups =",
"run(self): if not Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files = len(self.files)",
"Try and toggle back to global first if not Favs.toggle_global(win_id):",
"if not already added for n in names: if not",
"favorites self.add(self.name) elif value == 1: # Request new group",
"len(self.name) > 0: self.group_prompt() def file_prompt(self, view_code): # Add current",
"== Refresh.dummy_file: view.run_command('save') def run(self): refresh = True win_id =",
"self.num_files = len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) if",
"on disk; cannot add disk_omit_count += 1 if added: #",
"1) if replace: # Start with empty group for \"Replace",
"group if self.num_files: self.window.show_quick_panel( [\"Open Group\"] + self.files, lambda x:",
"file does not exist on disk!\" if disk_omit_count == 1",
"names.append(self.files[value - 1][1]) else: # Open global file names.append(self.files[value][1]) #",
"self.window.num_groups() > 1: group, idx = self.window.get_view_index(view) group_views = self.window.views_in_group(group)",
"through file list ensure they load in proper view index",
"!= None: if value == 0: # Single file name",
"== 0: # Single file name = view.file_name() if name",
"Favs.all_files(group_name=self.groups[value][0].replace(\"Group: \", \"\", 1)) self.num_files = len(self.files) self.groups = []",
"if view != None: view_code = 0 views = self.window.views()",
"not Favs.load(win_id=self.window.id()): # Present both files and groups for removal",
"group if value < self.num_files or (group and value <",
"to Favorites\") if view_code > 1: # Add all files",
"group for \"Replace Group\" selection Favs.add_group(group_name) # Add favorites self.add(self.name,",
"# Present group options self.window.show_quick_panel( self.group, self.group_answer ) def file_answer(self,",
"repeat = True elif Favs.exists(value, group=True): # Do not allow",
"else: # Only single file open, proceed without file options",
"without file options name = view.file_name() if name != None:",
"> 0: self.group_prompt() def file_prompt(self, view_code): # Add current active",
"sufficient v = self.window.show_input_panel( \"Create Group: \", \"New Group\", self.create_group,",
"again if name was not sufficient v = self.window.show_input_panel( \"Create",
") v.run_command(\"select_all\") elif value == 2: # \"Add to Group\"",
"global file name = self.files[value][1] # Remove file and save",
"Favs.remove_group(group_name) Favs.save(True) return else: # Remove group file name =",
"None: view_code = 0 views = self.window.views() # If there",
"# File does not exist on disk; cannot add disk_omit_count",
"Favs.exists(value, group=True): # Do not allow duplicates sublime.error_message(\"Group \\\"%s\\\" already",
"group; add file to favorites self.add(self.name) elif value == 1:",
"entire group if value < self.num_files or (group and value",
"[\"Remove Group\"] + self.files, lambda x: self.remove(x, group=True, group_name=group_name) )",
"group: if value == 0: # Open all files in",
"names and add them to group/global if not already added",
"self.window.open_file(Refresh.dummy_file) if view != None: Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda:",
"# Show availabe groups self.groups = Favs.all_groups() self.window.show_quick_panel( self.groups, lambda",
"= self.window.get_view_index(view) group_views = self.window.views_in_group(group) if len(group_views) > 1: view_code",
"# Single file name = view.file_name() if name != None:",
"if disk_omit_count: # Alert that files could be added message",
"does not exist:\\n%s\" % n) else: # Decend into group",
"some.\") def run(self): if not Favs.load(win_id=self.window.id()): self.files = Favs.all_files() self.num_files",
"create_group(self, value): repeat = False if value == \"\": #",
"# Start with empty group for \"Replace Group\" selection Favs.add_group(group_name)",
"+ self.files, lambda x: self.remove(x, group=True, group_name=group_name) ) else: sublime.error_message(\"No",
"specific group if self.window.num_groups() > 1: group, idx = self.window.get_view_index(view)",
"view.file_name() if path != None: if normpath(view.file_name()) == Refresh.dummy_file: #",
"= 0 added = 0 # Iterate names and add",
"files in group if self.num_files: self.window.show_quick_panel( [\"Open Group\"] + self.files,",
") v.run_command(\"select_all\") def select_group(self, value, replace=False): if value >= 0:",
"group_name=None): disk_omit_count = 0 added = 0 # Iterate names",
"Favs.group_count() > 0: # Options if groups already exit self.group",
"refresh file if more than one view is open if",
"self.group_prompt() if value == 2: # All files in layout",
"self.groups = [] self.num_groups = 0 # Show group files",
"len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) # Show panel",
"if self.num_files: self.window.show_quick_panel( [\"Open Group\"] + self.files, lambda x: self.open_file(x,",
"run(self): # Clean out all dead links if not Favs.load(clean=True,",
"value >= 0: active_group = self.window.active_group() if value < self.num_files",
"Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x: self.select_group(x, replace=replace) ) def group_answer(self,",
"if value == 2: # All files in layout group",
"1): # Open global file, file in group, or all",
"actual name sublime.error_message(\"Please provide a valid group name.\") repeat =",
"if value == 0: # Open all files in group",
"adding some.\") def run(self): if not Favs.load(win_id=self.window.id()): # Present both",
"value) if repeat: # Ask again if name was not",
"if groups already exit self.group += [\"Add to Group\", \"Replace",
"sublime.error_message(\"The following file does not exist:\\n%s\" % n) else: #",
"self.groups = [] self.num_groups = 0 # Show files in",
"+ self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.open_file )",
"allow duplicates sublime.error_message(\"Group \\\"%s\\\" already exists.\") repeat = True else:",
"= self.groups[value][0].replace(\"Group: \", \"\", 1) if replace: # Start with",
"than one group; if so allow saving of a specific",
"Close refresh file if more than one view is open",
"Favs.add_group(group_name) # Add favorites self.add(self.name, group_name) def show_groups(self, replace=False): #",
"save(self, view): if Refresh.on: path = view.file_name() if path !=",
"value == 0: # Open all files in group names",
"\"\", 1) self.files = Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups =",
"Start with empty group for \"Replace Group\" selection Favs.add_group(group_name) #",
"# Only single file open, proceed without file options name",
"Add current active file options = [\"Add Current File to",
"there is more than one view open allow saving all",
"view_code = 0 views = self.window.views() # If there is",
"group file name = self.files[value - 1][1] else: # Remove",
"global file names.append(self.files[value][1]) # Iterate through file list ensure they",
"file from global, file from group list, or entire group",
"path != None: if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def run(self):",
"Group\"] + self.files, lambda x: self.remove(x, group=True, group_name=group_name) ) else:",
"to Favorites\"] if view_code > 0: # Add all files",
"group, or all fiels in group names = [] if",
"name = v.file_name() if name != None: self.name.append(name) if len(self.name)",
"Try and toggle per project if refresh: view = self.window.open_file(Refresh.dummy_file)",
"= [] self.num_groups = 0 # Show files in group",
"+ self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.remove )",
"2 self.file_prompt(view_code) else: # Only single file open, proceed without",
"from favorites import Favorites Favs = Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class",
"Copyright (c) 2012 <NAME> <<EMAIL>> ''' import sublime import sublime_plugin",
"n in names: if exists(n): view = self.window.open_file(n) if view",
"def group_prompt(self): # Default options self.group = [\"No Group\", \"Create",
">= 0: self.window.set_view_index(view, active_group, count) count += 1 else: sublime.error_message(\"The",
"Group\"] # Present group options self.window.show_quick_panel( self.group, self.group_answer ) def",
"0: self.group_prompt() if value == 2: # All files in",
"if added: # Save if files were added Favs.save(True) if",
"if value == \"\": # Require an actual name sublime.error_message(\"Please",
"= Favs.all_groups() self.window.show_quick_panel( self.groups, lambda x: self.select_group(x, replace=replace) ) def",
"= self.window.views_in_group(group) if len(group_views) > 1: view_code = 2 self.file_prompt(view_code)",
"TODO: Widget views probably show up here too, maybe look",
"could be added message = \"1 file does not exist",
"name = view.file_name() if name != None: self.name.append(name) self.group_prompt() if",
"self.num_files = len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) #",
"def group_answer(self, value): if value >= 0: if value ==",
"self.window.id() if Refresh.on: Refresh.on = False refresh = False #",
"'FavoriteFiles', 'refresh.txt')) on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def run(self): #",
"range(0, self.num_files)] else: # Open file in group names.append(self.files[value -",
"= [] if view != None: view_code = 0 views",
"= 2 self.file_prompt(view_code) else: # Only single file open, proceed",
"if Refresh.on: path = view.file_name() if path != None: if",
"Remove file from global, file from group list, or entire",
"and toggle per project if refresh: view = self.window.open_file(Refresh.dummy_file) if",
"proper view index order count = 0 for n in",
"1: group, idx = self.window.get_view_index(view) group_views = self.window.views_in_group(group) if len(group_views)",
"allow saving all views # TODO: Widget views probably show",
"or (group and value < self.num_files + 1): name =",
"= True win_id = self.window.id() if Refresh.on: Refresh.on = False",
"if name was not sufficient v = self.window.show_input_panel( \"Create Group:",
"def show_groups(self, replace=False): # Show availabe groups self.groups = Favs.all_groups()",
"select_group(self, value, replace=False): if value >= 0: group_name = self.groups[value][0].replace(\"Group:",
"refresh = True win_id = self.window.id() if Refresh.on: Refresh.on =",
"= self.window.get_view_index(view) views = self.window.views_in_group(group) if len(views) > 0: for",
"if value >= 0: if value == 0: # No",
"if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def run(self): refresh = True",
"group=False): if value >= 0: active_group = self.window.active_group() if value",
"Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value,",
"disk_omit_count += 1 if added: # Save if files were",
"sublime.error_message(\"Please provide a valid group name.\") repeat = True elif",
"Favorites(join(sublime.packages_path(), 'User', 'favorite_files_list.json')) class Refresh: dummy_file = normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt'))",
"into exclduing them if len(views) > 1: view_code = 1",
"self.num_groups > 0: self.window.show_quick_panel( self.files + self.groups, self.remove ) else:",
"if value == 1: # All files in window views",
"= normpath(join(sublime.packages_path(), 'FavoriteFiles', 'refresh.txt')) on = False class CleanOrphanedFavoritesCommand(sublime_plugin.WindowCommand): def",
"self.num_groups = 0 # Show group files if self.num_files: self.window.show_quick_panel(",
"Open global file names.append(self.files[value][1]) # Iterate through file list ensure",
"not Favs.load(clean=True, win_id=self.window.id()): Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self,",
"Open all files in group names = [self.files[x][1] for x",
"view = self.window.open_file(n) if view != None: if active_group >=",
"groups already exit self.group += [\"Add to Group\", \"Replace Group\"]",
"True win_id = self.window.id() if Refresh.on: Refresh.on = False refresh",
"== \"\": # Require an actual name sublime.error_message(\"Please provide a",
"if there is more than one group; if so allow",
"and value < self.num_files + 1): # Open global file,",
"[] self.num_groups = 0 # Show files in group if",
"import join, exists, normpath from favorites import Favorites Favs =",
"in layout group group, idx = self.window.get_view_index(view) views = self.window.views_in_group(group)",
"elif value == 3: # \"Replace Group\" self.show_groups(replace=True) def group_prompt(self):",
"0: for v in views: name = v.file_name() if name",
"names = [] if group: if value == 0: #",
"== None: return if value == 0: # Remove group",
"self.files + self.groups, self.remove ) else: sublime.error_message(\"No favorites to remove!\")",
"options.append(\"Add All Files to in Active Group to Favorites\") #",
"if self.window.num_groups() > 1: group, idx = self.window.get_view_index(view) group_views =",
"views = self.window.views_in_group(group) if len(views) > 0: for v in",
"win_id = self.window.id() if Refresh.on: Refresh.on = False refresh =",
"# Alert that files could be added message = \"1",
"groups for removal self.files = Favs.all_files() self.num_files = len(self.files) self.groups",
"Remove global file name = self.files[value][1] # Remove file and",
"!= None: Refresh.on = True self.window.focus_view(view) sublime.set_timeout(lambda: self.save(view), 100) else:",
"Group\", \"Create Group\"] if Favs.group_count() > 0: # Options if",
"Group\", self.create_group, None, None ) v.run_command(\"select_all\") def select_group(self, value, replace=False):",
"names = [self.files[x][1] for x in range(0, self.num_files)] else: #",
"None: if normpath(view.file_name()) == Refresh.dummy_file: # Close refresh file if",
"self.window.set_view_index(view, active_group, count) count += 1 else: sublime.error_message(\"The following file",
"self.groups[value][0].replace(\"Group: \", \"\", 1) self.files = Favs.all_files(group_name=group_name) self.num_files = len(self.files)",
"save Favs.remove(name, group_name=group_name) Favs.save(True) else: # Decend into group value",
"view is open if len(view.window().views()) > 1: sublime.set_timeout(lambda: sublime.active_window().run_command(\"close_file\"), 100)",
"def run(self): refresh = True win_id = self.window.id() if Refresh.on:",
"Single file name = view.file_name() if name != None: self.name.append(name)",
"order count = 0 for n in names: if exists(n):",
"self.groups, self.open_file ) else: sublime.error_message(\"No favorites found! Try adding some.\")",
"\"Replace Group\"] # Present group options self.window.show_quick_panel( self.group, self.group_answer )",
"file open, proceed without file options name = view.file_name() if",
"class TogglePerProjectFavoritesCommand(sublime_plugin.WindowCommand): def save(self, view): if Refresh.on: path = view.file_name()",
"name != None: self.name.append(name) if len(self.name) > 0: self.group_prompt() def",
"self.num_files group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) self.files = Favs.all_files(group_name=group_name)",
"single file open, proceed without file options name = view.file_name()",
"favorites self.add(self.name, group_name) def show_groups(self, replace=False): # Show availabe groups",
"open, proceed without file options name = view.file_name() if name",
"[self.files[x][1] for x in range(0, self.num_files)] else: # Open file",
"+ self.groups, self.open_file ) else: sublime.error_message(\"No favorites found! Try adding",
"Request new group name v = self.window.show_input_panel( \"Create Group: \",",
"files in window views = self.window.views() if len(views) > 0:",
"value == 1: # Request new group name v =",
"views # TODO: Widget views probably show up here too,",
"a specific group if self.window.num_groups() > 1: group, idx =",
"return else: # Remove group file name = self.files[value -",
"\"1 file does not exist on disk!\" if disk_omit_count ==",
"group_name=group_name): if exists(n): Favs.set(n, group_name=group_name) added += 1 else: #",
"= len(self.files) self.groups = Favs.all_groups() self.num_groups = len(self.groups) if self.num_files",
"in window options.append(\"Add All Files to Favorites\") if view_code >",
"group value -= self.num_files group_name = self.groups[value][0].replace(\"Group: \", \"\", 1)",
"1: view_code = 2 self.file_prompt(view_code) else: # Only single file",
"view.run_command('save') def run(self): refresh = True win_id = self.window.id() if",
"if view != None: if value == 0: # Single",
"2: # \"Add to Group\" self.show_groups() elif value == 3:",
"value): repeat = False if value == \"\": # Require",
"self.num_groups = 0 # Show files in group if self.num_files:",
"0: group_name = self.groups[value][0].replace(\"Group: \", \"\", 1) if replace: #",
"following file does not exist:\\n%s\" % n) else: # Decend",
"def file_answer(self, value): if value >= 0: view = self.window.active_view()",
"files if self.num_files: self.window.show_quick_panel( [\"Remove Group\"] + self.files, lambda x:",
"Favorites\"] if view_code > 0: # Add all files in",
"== 0: # Remove group Favs.remove_group(group_name) Favs.save(True) return else: #",
"file options name = view.file_name() if name != None: self.name.append(name)",
"toggle per project if refresh: view = self.window.open_file(Refresh.dummy_file) if view",
"is more than one view open allow saving all views",
"favorites to remove!\") class FavoritesForceRefreshListenerCommand(sublime_plugin.EventListener): def on_post_save(self, view): if Refresh.on:",
"Group to Favorites\") # Preset file options self.window.show_quick_panel( options, self.file_answer",
"self.window.show_quick_panel( self.groups, lambda x: self.select_group(x, replace=replace) ) def group_answer(self, value):",
"1 else: sublime.error_message(\"The following file does not exist:\\n%s\" % n)",
"name.\") repeat = True elif Favs.exists(value, group=True): # Do not",
"group=False, group_name=None): if value >= 0: # Remove file from",
"view index order count = 0 for n in names:",
"= 0 # Iterate names and add them to group/global",
"\"Replace Group\" self.show_groups(replace=True) def group_prompt(self): # Default options self.group =",
"else: # Decend into group value -= self.num_files self.files =",
"Favs.remove(name, group_name=group_name) Favs.save(True) else: # Decend into group value -=",
"< self.num_files + 1): name = None if group: if",
"group list, or entire group if value < self.num_files or",
"repeat: # Ask again if name was not sufficient v",
"names, group_name=None): disk_omit_count = 0 added = 0 # Iterate",
"1 else: # File does not exist on disk; cannot",
"active_group >= 0: self.window.set_view_index(view, active_group, count) count += 1 else:",
"Favs.load(force=True, clean=True, win_id=self.window.id()) class SelectFavoriteFileCommand(sublime_plugin.WindowCommand): def open_file(self, value, group=False): if",
"all fiels in group names = [] if group: if",
"def add(self, names, group_name=None): disk_omit_count = 0 added = 0",
"# Iterate names and add them to group/global if not",
"!= None: self.name.append(name) self.group_prompt() if value == 1: # All",
"name v = self.window.show_input_panel( \"Create Group: \", \"New Group\", self.create_group,",
"\", \"\", 1) self.files = Favs.all_files(group_name=group_name) self.num_files = len(self.files) self.groups",
"file name = view.file_name() if name != None: self.name.append(name) self.group_prompt()",
"x: self.remove(x, group=True, group_name=group_name) ) else: sublime.error_message(\"No favorites found! Try",
"view.file_name() if name != None: self.name.append(name) self.group_prompt() if value ==",
"All files in layout group group, idx = self.window.get_view_index(view) views",
"[] if group: if value == 0: # Open all",
"if exists(n): view = self.window.open_file(n) if view != None: if",
"0: # Open all files in group names = [self.files[x][1]",
"# Request new group name v = self.window.show_input_panel( \"Create Group:",
"disk; cannot add disk_omit_count += 1 if added: # Save",
"were added Favs.save(True) if disk_omit_count: # Alert that files could",
"self.num_groups = len(self.groups) # Show panel if self.num_files + self.num_groups",
"1)) self.num_files = len(self.files) self.groups = [] self.num_groups = 0",
"if disk_omit_count == 1 else \"%d file(s) do not exist",
"0: # No group; add file to favorites self.add(self.name) elif",
"# \"Add to Group\" self.show_groups() elif value == 3: #",
"0: self.group_prompt() def file_prompt(self, view_code): # Add current active file",
"found! Try adding some.\") class AddFavoriteFileCommand(sublime_plugin.WindowCommand): def add(self, names, group_name=None):",
"with empty group for \"Replace Group\" selection Favs.add_group(group_name) # Add",
"added += 1 else: # File does not exist on",
"# Remove global file name = self.files[value][1] # Remove file",
"= Favs.all_groups() self.num_groups = len(self.groups) # Show panel if self.num_files",
"count = 0 for n in names: if exists(n): view",
"\", \"New Group\", self.create_group, None, None ) v.run_command(\"select_all\") elif value",
"Save if files were added Favs.save(True) if disk_omit_count: # Alert",
"- 1][1] else: # Remove global file name = self.files[value][1]",
"[\"Add Current File to Favorites\"] if view_code > 0: #",
"1: view_code = 1 # See if there is more",
"self.window.active_group() if value < self.num_files or (group and value <",
"if name != None: self.name.append(name) self.group_prompt() if value == 1:",
"proceed without file options name = view.file_name() if name !=",
"self.window.show_quick_panel( [\"Remove Group\"] + self.files, lambda x: self.remove(x, group=True, group_name=group_name)",
"views = self.window.views() # If there is more than one",
"a project file!') else: Favs.open(win_id=self.window.id()) def is_enabled(self): return sublime.load_settings(\"favorite_files.sublime-settings\").get(\"enable_per_projects\", False)",
"in group names.append(self.files[value - 1][1]) else: # Open global file",
"group_views = self.window.views_in_group(group) if len(group_views) > 1: view_code = 2",
"== 2: # \"Add to Group\" self.show_groups() elif value ==",
"and toggle back to global first if not Favs.toggle_global(win_id): return",
"value, group=False, group_name=None): if value >= 0: # Remove file",
"if so allow saving of a specific group if self.window.num_groups()",
"# Ask again if name was not sufficient v =",
"names.append(self.files[value][1]) # Iterate through file list ensure they load in",
"into group value -= self.num_files group_name = self.groups[value][0].replace(\"Group: \", \"\",",
"self.num_groups = len(self.groups) if self.num_files + self.num_groups > 0: self.window.show_quick_panel(",
"!= None: if normpath(view.file_name()) == Refresh.dummy_file: view.run_command('save') def run(self): refresh",
"do not exist on disk!\" % disk_omit_count sublime.error_message(message) def create_group(self,",
"self.group = [\"No Group\", \"Create Group\"] if Favs.group_count() > 0:",
"probably show up here too, maybe look into exclduing them",
"group; if so allow saving of a specific group if",
"value == 2: # \"Add to Group\" self.show_groups() elif value",
"- 1][1]) else: # Open global file names.append(self.files[value][1]) # Iterate"
] |
[
"== list03(0, 1 ,2) assert 5 == list03(2, 1 ,3)",
"from polyphony import testbench def list03(x, y, z): a =",
"x r1 = y a[r0] = a[r1] + z return",
"= [1, 2, 3] r0 = x r1 = y",
"y a[r0] = a[r1] + z return a[r0] @testbench def",
"<filename>tests/list/list03.py from polyphony import testbench def list03(x, y, z): a",
"= a[r1] + z return a[r0] @testbench def test(): assert",
"testbench def list03(x, y, z): a = [1, 2, 3]",
"def test(): assert 4 == list03(0, 1 ,2) assert 5",
"r1 = y a[r0] = a[r1] + z return a[r0]",
"return a[r0] @testbench def test(): assert 4 == list03(0, 1",
"y, z): a = [1, 2, 3] r0 = x",
"a = [1, 2, 3] r0 = x r1 =",
"@testbench def test(): assert 4 == list03(0, 1 ,2) assert",
"z return a[r0] @testbench def test(): assert 4 == list03(0,",
"a[r0] @testbench def test(): assert 4 == list03(0, 1 ,2)",
"test(): assert 4 == list03(0, 1 ,2) assert 5 ==",
"polyphony import testbench def list03(x, y, z): a = [1,",
"list03(x, y, z): a = [1, 2, 3] r0 =",
"= y a[r0] = a[r1] + z return a[r0] @testbench",
"list03(0, 1 ,2) assert 5 == list03(2, 1 ,3) test()",
"+ z return a[r0] @testbench def test(): assert 4 ==",
"4 == list03(0, 1 ,2) assert 5 == list03(2, 1",
"a[r1] + z return a[r0] @testbench def test(): assert 4",
"a[r0] = a[r1] + z return a[r0] @testbench def test():",
"= x r1 = y a[r0] = a[r1] + z",
"def list03(x, y, z): a = [1, 2, 3] r0",
"r0 = x r1 = y a[r0] = a[r1] +",
"z): a = [1, 2, 3] r0 = x r1",
"[1, 2, 3] r0 = x r1 = y a[r0]",
"2, 3] r0 = x r1 = y a[r0] =",
"3] r0 = x r1 = y a[r0] = a[r1]",
"assert 4 == list03(0, 1 ,2) assert 5 == list03(2,",
"import testbench def list03(x, y, z): a = [1, 2,"
] |
[
"(sc2.Race(r[0]), r[1]) for r in race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id",
"( (sc2.Race(r[0]), r[1]) for r in race_breakdown ) ctx['version'] =",
"played and winrate for each member games_played = self.queryset.annotate( games_played=dm.F('wins')",
"def get_context_data(self, **kwargs): ctx = super(BaseView, self).get_context_data(**kwargs) # Get links",
"models as dm from django.shortcuts import get_object_or_404, render from django.views.generic.list",
"Get links so we can display links to admin. class",
"def get_context_data(self, **kwargs): ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter(",
"r[1]) for r in race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id return",
"= 'sc2clanman/members.html' # No ordering since it's done by the",
"ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time",
"= models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model",
"import TemplateView from django.utils.decorators import method_decorator from . import models,",
"self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1]) for r",
"class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model = 'clanwar' def get_context_data(self,",
"display links to admin. class Opts(object): app_label = 'sc2clanman' model_name",
"games_played = self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first()",
"return super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView): \"\"\" Combines BaseView",
"template_name = 'sc2clanman/members.html' # No ordering since it's done by",
"BaseView): \"\"\" Combines BaseView with capability to show a paginated",
"\"\"\" pass class MemberView(ListView): \"\"\" Show the clanmembers in a",
"return ctx class AuthenticatedView(BaseView): \"\"\" BaseView subclass with the login",
"success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate",
"= self.request.user.is_superuser or self.request.user.is_staff return ctx class AuthenticatedView(BaseView): \"\"\" BaseView",
"capability to show a paginated object list \"\"\" pass class",
"= models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True",
"BaseView(TemplateView): \"\"\" A TemplateView subclass which adds the Opts object",
"get_context_data(self, **kwargs): ctx = super(BaseView, self).get_context_data(**kwargs) # Get links so",
"super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] =",
"import Counter from django.conf import settings from django.contrib.auth.decorators import login_required,",
"class AuthenticatedView(BaseView): \"\"\" BaseView subclass with the login required decorator",
"A TemplateView subclass which adds the Opts object to context.",
"super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView): template_name",
"\"\"\" Combines BaseView with capability to show a paginated object",
"= ( (sc2.League(l[0]), l[1]) for l in league_breakdown ) ctx['country_breakdown']",
"sc2, mixins class BaseView(TemplateView): \"\"\" A TemplateView subclass which adds",
"wins and losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum']",
"stats # Game stats - aggregate and sum wins and",
"adds the Opts object to context. \"\"\" current_model = 'clanmember'",
"ctx class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model = 'clanwar' def",
"in race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView):",
"or self.request.user.is_staff return ctx class AuthenticatedView(BaseView): \"\"\" BaseView subclass with",
"by the front-end queryset = models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx",
"apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model =",
"Annotate games played and winrate for each member games_played =",
"ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last game date ctx['least_passionate'] = self.queryset.order_by('last_game').first()",
"'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] =",
"# Calculate quick stats # Game stats - aggregate and",
"for each member games_played = self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played')",
"prominent league, country and race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True)",
"django.contrib.auth.decorators import login_required, permission_required from django.db import models as dm",
"ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model = 'clanwar' def get_context_data(self, **kwargs):",
"self.queryset.order_by('last_game').first() # Most prominent league, country and race league_breakdown =",
"Opts object to context. \"\"\" current_model = 'clanmember' def get_context_data(self,",
"import login_required, permission_required from django.db import models as dm from",
"import models as dm from django.shortcuts import get_object_or_404, render from",
"= super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update']",
"class Opts(object): app_label = 'sc2clanman' model_name = self.current_model ctx['opts'] =",
"quick stats # Game stats - aggregate and sum wins",
"= Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1])",
"= super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView):",
"race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] = (",
"\"\"\" current_model = 'clanmember' def get_context_data(self, **kwargs): ctx = super(BaseView,",
"'sc2clanman' model_name = self.current_model ctx['opts'] = Opts() ctx['is_authorized'] = self.request.user.is_superuser",
"from django.views.generic.list import BaseListView from django.views.generic import TemplateView from django.utils.decorators",
"game date ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most prominent league, country",
"python3 from collections import Counter from django.conf import settings from",
"**kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView): \"\"\" Combines",
"permission_required from django.db import models as dm from django.shortcuts import",
"object list \"\"\" pass class MemberView(ListView): \"\"\" Show the clanmembers",
"r in race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id return ctx class",
"ctx class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model = 'clanwar' def",
"models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time",
"action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time #",
"super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView): \"\"\" Combines BaseView with",
"dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum'] # Annotate games played",
"dm from django.shortcuts import get_object_or_404, render from django.views.generic.list import BaseListView",
"the front-end queryset = models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx =",
"links to admin. class Opts(object): app_label = 'sc2clanman' model_name =",
"**kwargs): ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True,",
"country and race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown']",
"current_model = 'clanmember' def get_context_data(self, **kwargs): ctx = super(BaseView, self).get_context_data(**kwargs)",
"Most prominent league, country and race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league',",
").most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] = (",
"django.utils.decorators import method_decorator from . import models, apps, sc2, mixins",
"paginated object list \"\"\" pass class MemberView(ListView): \"\"\" Show the",
"models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate quick stats # Game",
"= gp['wins__sum'] + gp['losses__sum'] # Annotate games played and winrate",
"losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum']",
"*args, **kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView): \"\"\"",
"can display links to admin. class Opts(object): app_label = 'sc2clanman'",
"def get_context_data(self, **kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all()",
"flat=True) ).most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1]) for r in",
"and race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] =",
"ctx['version'] = apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html'",
"'clanmember' def get_context_data(self, **kwargs): ctx = super(BaseView, self).get_context_data(**kwargs) # Get",
"pass class MemberView(ListView): \"\"\" Show the clanmembers in a list",
"gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum'] #",
"**kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id')) ctx['clan_tag']",
"ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model = 'clanwar' def get_context_data(self, **kwargs):",
"Opts() ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff return ctx class AuthenticatedView(BaseView):",
"ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most prominent league, country and race",
"required decorator applied. \"\"\" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return",
"self.current_model ctx['opts'] = Opts() ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff return",
"a list ordered by ladder score\"\"\" template_name = 'sc2clanman/members.html' #",
"= self.current_model ctx['opts'] = Opts() ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff",
"from django.conf import settings from django.contrib.auth.decorators import login_required, permission_required from",
"class ListView(BaseListView, BaseView): \"\"\" Combines BaseView with capability to show",
"= 'sc2clanman' model_name = self.current_model ctx['opts'] = Opts() ctx['is_authorized'] =",
"self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter(",
"race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]),",
"ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return ctx class",
"to show a paginated object list \"\"\" pass class MemberView(ListView):",
"done by the front-end queryset = models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs):",
") ctx['version'] = apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView): template_name =",
"in a list ordered by ladder score\"\"\" template_name = 'sc2clanman/members.html'",
"from django.db import models as dm from django.shortcuts import get_object_or_404,",
"Calculate quick stats # Game stats - aggregate and sum",
"Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1]) for",
"admin. class Opts(object): app_label = 'sc2clanman' model_name = self.current_model ctx['opts']",
"model_name = self.current_model ctx['opts'] = Opts() ctx['is_authorized'] = self.request.user.is_superuser or",
"= models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update']",
"return ctx class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model = 'clanwar'",
"the clanmembers in a list ordered by ladder score\"\"\" template_name",
"template_name = 'sc2clanman/cwdetail.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx",
"= 'sc2clanman/cw.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx =",
"by ladder score\"\"\" template_name = 'sc2clanman/members.html' # No ordering since",
").order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last game",
"= 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars']",
"BaseView subclass with the login required decorator applied. \"\"\" @method_decorator(login_required)",
"object to context. \"\"\" current_model = 'clanmember' def get_context_data(self, **kwargs):",
"from django.views.generic import TemplateView from django.utils.decorators import method_decorator from .",
"render from django.views.generic.list import BaseListView from django.views.generic import TemplateView from",
"\"\"\" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs)",
"'sc2clanman/cwdetail.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarDetailView,",
").most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1]) for r in race_breakdown",
"list ordered by ladder score\"\"\" template_name = 'sc2clanman/members.html' # No",
"django.shortcuts import get_object_or_404, render from django.views.generic.list import BaseListView from django.views.generic",
"member games_played = self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played'] =",
"front-end queryset = models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx = super(MemberView,",
"and losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] +",
"queryset = models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx = super(MemberView, self).get_context_data(**kwargs)",
").most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1]) for l in league_breakdown",
"= games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last game date ctx['least_passionate']",
"from django.utils.decorators import method_decorator from . import models, apps, sc2,",
"**kwargs): ctx = super(BaseView, self).get_context_data(**kwargs) # Get links so we",
"login required decorator applied. \"\"\" @method_decorator(login_required) def dispatch(self, *args, **kwargs):",
"Game stats - aggregate and sum wins and losses gp",
") ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown = Counter(",
"context. \"\"\" current_model = 'clanmember' def get_context_data(self, **kwargs): ctx =",
"login_required, permission_required from django.db import models as dm from django.shortcuts",
"mixins class BaseView(TemplateView): \"\"\" A TemplateView subclass which adds the",
"def dispatch(self, *args, **kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView,",
"get_context_data(self, **kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id'))",
"and winrate for each member games_played = self.queryset.annotate( games_played=dm.F('wins') +",
"the login required decorator applied. \"\"\" @method_decorator(login_required) def dispatch(self, *args,",
"games_played.order_by('-games_played').first() # Last game date ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most",
"(sc2.League(l[0]), l[1]) for l in league_breakdown ) ctx['country_breakdown'] = Counter(",
"Combines BaseView with capability to show a paginated object list",
"ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC, success=True, ).order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC,",
"= 'clanmember' def get_context_data(self, **kwargs): ctx = super(BaseView, self).get_context_data(**kwargs) #",
"l in league_breakdown ) ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common()",
"ordering since it's done by the front-end queryset = models.ClanMember.clanmembers.all()",
"= super(BaseView, self).get_context_data(**kwargs) # Get links so we can display",
"list \"\"\" pass class MemberView(ListView): \"\"\" Show the clanmembers in",
"to context. \"\"\" current_model = 'clanmember' def get_context_data(self, **kwargs): ctx",
"ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last game date",
"success=True ).order_by('-time')[0].time # Calculate quick stats # Game stats -",
"= self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played']",
"it's done by the front-end queryset = models.ClanMember.clanmembers.all() def get_context_data(self,",
"class MemberView(ListView): \"\"\" Show the clanmembers in a list ordered",
"BaseListView from django.views.generic import TemplateView from django.utils.decorators import method_decorator from",
"current_model = 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs)",
"= 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw']",
"( (sc2.League(l[0]), l[1]) for l in league_breakdown ) ctx['country_breakdown'] =",
"collections import Counter from django.conf import settings from django.contrib.auth.decorators import",
"the Opts object to context. \"\"\" current_model = 'clanmember' def",
"games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last game date ctx['least_passionate'] =",
"ctx class AuthenticatedView(BaseView): \"\"\" BaseView subclass with the login required",
"Counter from django.conf import settings from django.contrib.auth.decorators import login_required, permission_required",
"= super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id')) ctx['clan_tag'] = settings.SC2_CLANMANAGER_CLAN_TAG",
"MemberView(ListView): \"\"\" Show the clanmembers in a list ordered by",
"**kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return ctx",
"+ dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() #",
"Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4)",
"ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1]) for r in race_breakdown )",
"league, country and race league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common()",
"django.views.generic.list import BaseListView from django.views.generic import TemplateView from django.utils.decorators import",
"BaseView with capability to show a paginated object list \"\"\"",
"ListView(BaseListView, BaseView): \"\"\" Combines BaseView with capability to show a",
"models, apps, sc2, mixins class BaseView(TemplateView): \"\"\" A TemplateView subclass",
"from collections import Counter from django.conf import settings from django.contrib.auth.decorators",
"# Last game date ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most prominent",
"l[1]) for l in league_breakdown ) ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country',",
"self.request.user.is_staff return ctx class AuthenticatedView(BaseView): \"\"\" BaseView subclass with the",
"dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first() # Last",
"AuthenticatedView(BaseView): \"\"\" BaseView subclass with the login required decorator applied.",
"django.views.generic import TemplateView from django.utils.decorators import method_decorator from . import",
"ctx['opts'] = Opts() ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff return ctx",
"ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum'] # Annotate games played and",
"with the login required decorator applied. \"\"\" @method_decorator(login_required) def dispatch(self,",
"self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView): template_name =",
"= self.queryset.order_by('last_game').first() # Most prominent league, country and race league_breakdown",
"Last game date ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most prominent league,",
"get_context_data(self, **kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] = models.ClanWar.objects.all() return",
"= Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True)",
"ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id')) ctx['clan_tag'] =",
").order_by('-time')[0].time # Calculate quick stats # Game stats - aggregate",
"dispatch(self, *args, **kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView):",
"= apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model",
"'sc2clanman/cw.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarView,",
"\"\"\" A TemplateView subclass which adds the Opts object to",
"'sc2clanman/members.html' # No ordering since it's done by the front-end",
"ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate quick stats",
"games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] = games_played.order_by('-games_played').first()",
"self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown']",
"gp['losses__sum'] # Annotate games played and winrate for each member",
"# Get links so we can display links to admin.",
"winrate for each member games_played = self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses')",
"# Annotate games played and winrate for each member games_played",
"action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate quick stats # Game stats",
"import get_object_or_404, render from django.views.generic.list import BaseListView from django.views.generic import",
"settings from django.contrib.auth.decorators import login_required, permission_required from django.db import models",
"self).dispatch(*args, **kwargs) class ListView(BaseListView, BaseView): \"\"\" Combines BaseView with capability",
"current_model = 'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs)",
"models.ClanMember.clanmembers.all() def get_context_data(self, **kwargs): ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] =",
"subclass with the login required decorator applied. \"\"\" @method_decorator(login_required) def",
"from . import models, apps, sc2, mixins class BaseView(TemplateView): \"\"\"",
"No ordering since it's done by the front-end queryset =",
"import models, apps, sc2, mixins class BaseView(TemplateView): \"\"\" A TemplateView",
"a paginated object list \"\"\" pass class MemberView(ListView): \"\"\" Show",
"- aggregate and sum wins and losses gp = self.queryset.aggregate(dm.Sum('wins'),",
"Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1]) for",
"aggregate and sum wins and losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses'))",
"subclass which adds the Opts object to context. \"\"\" current_model",
"template_name = 'sc2clanman/cw.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx",
"class BaseView(TemplateView): \"\"\" A TemplateView subclass which adds the Opts",
"date ctx['least_passionate'] = self.queryset.order_by('last_game').first() # Most prominent league, country and",
"ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1]) for l in league_breakdown )",
"models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model =",
"which adds the Opts object to context. \"\"\" current_model =",
"TemplateView from django.utils.decorators import method_decorator from . import models, apps,",
"in league_breakdown ) ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown",
").order_by('-time')[0].time ctx['last_detail_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate quick",
"**kwargs) class ListView(BaseListView, BaseView): \"\"\" Combines BaseView with capability to",
"flat=True) ).most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1]) for l in",
"self.request.user.is_superuser or self.request.user.is_staff return ctx class AuthenticatedView(BaseView): \"\"\" BaseView subclass",
"as dm from django.shortcuts import get_object_or_404, render from django.views.generic.list import",
"TemplateView subclass which adds the Opts object to context. \"\"\"",
"Opts(object): app_label = 'sc2clanman' model_name = self.current_model ctx['opts'] = Opts()",
"class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html' current_model = 'clanwar' def get_context_data(self,",
"= Opts() ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff return ctx class",
"get_context_data(self, **kwargs): ctx = super(MemberView, self).get_context_data(**kwargs) ctx['last_member_update'] = models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_SYNC,",
"@method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AuthenticatedView, self).dispatch(*args, **kwargs) class",
"each member games_played = self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played']",
"import BaseListView from django.views.generic import TemplateView from django.utils.decorators import method_decorator",
"method_decorator from . import models, apps, sc2, mixins class BaseView(TemplateView):",
"\"\"\" BaseView subclass with the login required decorator applied. \"\"\"",
"stats - aggregate and sum wins and losses gp =",
"race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id return ctx class ClanWarView(BaseView): template_name",
"super(BaseView, self).get_context_data(**kwargs) # Get links so we can display links",
"ladder score\"\"\" template_name = 'sc2clanman/members.html' # No ordering since it's",
"since it's done by the front-end queryset = models.ClanMember.clanmembers.all() def",
"super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id')) ctx['clan_tag'] = settings.SC2_CLANMANAGER_CLAN_TAG return",
"show a paginated object list \"\"\" pass class MemberView(ListView): \"\"\"",
"'clanwar' def get_context_data(self, **kwargs): ctx = super(ClanWarView, self).get_context_data(**kwargs) ctx['clanwars'] =",
"import method_decorator from . import models, apps, sc2, mixins class",
"django.conf import settings from django.contrib.auth.decorators import login_required, permission_required from django.db",
"league_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]),",
"import settings from django.contrib.auth.decorators import login_required, permission_required from django.db import",
"league_breakdown ) ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown =",
"# Game stats - aggregate and sum wins and losses",
"games played and winrate for each member games_played = self.queryset.annotate(",
"+ gp['losses__sum'] # Annotate games played and winrate for each",
"= Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] = ( (sc2.Race(r[0]), r[1])",
"Show the clanmembers in a list ordered by ladder score\"\"\"",
"self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum'] # Annotate games",
"and sum wins and losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played']",
"self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar, id=kwargs.get('cw_id')) ctx['clan_tag'] = settings.SC2_CLANMANAGER_CLAN_TAG return ctx",
"to admin. class Opts(object): app_label = 'sc2clanman' model_name = self.current_model",
"#!/bin/env python3 from collections import Counter from django.conf import settings",
"applied. \"\"\" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AuthenticatedView, self).dispatch(*args,",
"def get_context_data(self, **kwargs): ctx = super(ClanWarDetailView, self).get_context_data(**kwargs) ctx['cw'] = get_object_or_404(models.ClanWar,",
"return ctx class ClanWarView(BaseView): template_name = 'sc2clanman/cw.html' current_model = 'clanwar'",
"= models.SyncLog.objects.filter( action=models.SyncLog.CLAN_MEMBER_DETAIL_SYNC, success=True ).order_by('-time')[0].time # Calculate quick stats #",
"from django.shortcuts import get_object_or_404, render from django.views.generic.list import BaseListView from",
"we can display links to admin. class Opts(object): app_label =",
"= games_played.order_by('-games_played').first() # Last game date ctx['least_passionate'] = self.queryset.order_by('last_game').first() #",
"ordered by ladder score\"\"\" template_name = 'sc2clanman/members.html' # No ordering",
"from django.contrib.auth.decorators import login_required, permission_required from django.db import models as",
"score\"\"\" template_name = 'sc2clanman/members.html' # No ordering since it's done",
"ctx = super(BaseView, self).get_context_data(**kwargs) # Get links so we can",
"so we can display links to admin. class Opts(object): app_label",
"flat=True) ).most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race', flat=True) ).most_common(4) ctx['race_breakdown'] =",
"= ( (sc2.Race(r[0]), r[1]) for r in race_breakdown ) ctx['version']",
"ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True) ).most_common() race_breakdown = Counter( self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('race',",
"= 'sc2clanman/cwdetail.html' current_model = 'clanwar' def get_context_data(self, **kwargs): ctx =",
"clanmembers in a list ordered by ladder score\"\"\" template_name =",
"self.queryset.annotate( games_played=dm.F('wins') + dm.F('losses') ).order_by('games_played') ctx['least_games_played'] = games_played.filter(games_played__gt=0).first() ctx['most_games_played'] =",
"# Most prominent league, country and race league_breakdown = Counter(",
"django.db import models as dm from django.shortcuts import get_object_or_404, render",
"get_object_or_404, render from django.views.generic.list import BaseListView from django.views.generic import TemplateView",
". import models, apps, sc2, mixins class BaseView(TemplateView): \"\"\" A",
"self.queryset.exclude(score=models.ClanMember.SCORE_UNRANKED).values_list('league', flat=True) ).most_common() ctx['league_breakdown'] = ( (sc2.League(l[0]), l[1]) for l",
"= self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] = gp['wins__sum'] + gp['losses__sum'] # Annotate",
"with capability to show a paginated object list \"\"\" pass",
"links so we can display links to admin. class Opts(object):",
"decorator applied. \"\"\" @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AuthenticatedView,",
"sum wins and losses gp = self.queryset.aggregate(dm.Sum('wins'), dm.Sum('losses')) ctx['total_games_played'] =",
"ctx['is_authorized'] = self.request.user.is_superuser or self.request.user.is_staff return ctx class AuthenticatedView(BaseView): \"\"\"",
"apps, sc2, mixins class BaseView(TemplateView): \"\"\" A TemplateView subclass which",
"for r in race_breakdown ) ctx['version'] = apps.ClanManConfig.version_id return ctx",
"<reponame>paskausks/sc2cm #!/bin/env python3 from collections import Counter from django.conf import",
"app_label = 'sc2clanman' model_name = self.current_model ctx['opts'] = Opts() ctx['is_authorized']",
"\"\"\" Show the clanmembers in a list ordered by ladder",
"ctx['clanwars'] = models.ClanWar.objects.all() return ctx class ClanWarDetailView(BaseView): template_name = 'sc2clanman/cwdetail.html'",
"self).get_context_data(**kwargs) # Get links so we can display links to",
"for l in league_breakdown ) ctx['country_breakdown'] = Counter( self.queryset.exclude(country='').values_list('country', flat=True)",
"gp['wins__sum'] + gp['losses__sum'] # Annotate games played and winrate for",
"# No ordering since it's done by the front-end queryset"
] |
[
"{ \"t_range\": [0, 1, 0.1], \"min_samples\": 10, \"epsilon\": 1e-8, #",
"return self class FunctionGraph(ParametricCurve): CONFIG = { \"color\": YELLOW, \"x_range\":",
"kwargs) if t_range is not None: self.t_range[:len(t_range)] = t_range #",
"for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2,",
"return self.t_func(t) def init_points(self): t_min, t_max, step = self.t_range jumps",
"self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ]",
"self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func = t_func VMobject.__init__(self,",
"from manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject):",
"backward compatible with all the scenes specifying t_min, t_max, step_size",
"self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps > t_min) &",
"t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step),",
"**kwargs) def get_function(self): return self.function def get_point_from_function(self, x): return self.t_func(x)",
"= [*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t) for t",
"t_min, t_max, step = self.t_range jumps = np.array(self.discontinuities) jumps =",
"0] super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self): return self.function def get_point_from_function(self,",
"zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2] points =",
"] self.t_func = t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self, t): return",
"boundary_times = [t_min, t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)]",
"FunctionGraph(ParametricCurve): CONFIG = { \"color\": YELLOW, \"x_range\": [-8, 8, 0.25],",
"= [t_min, t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort()",
"init_points(self): t_min, t_max, step = self.t_range jumps = np.array(self.discontinuities) jumps",
"CONFIG = { \"color\": YELLOW, \"x_range\": [-8, 8, 0.25], }",
"(jumps < t_max)] boundary_times = [t_min, t_max, *(jumps - self.epsilon),",
"in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2] points",
"kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func = t_func VMobject.__init__(self, **kwargs)",
"import digest_config from manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject): CONFIG =",
"t_max, step = self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps",
"in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return self class",
"t_min) & (jumps < t_max)] boundary_times = [t_min, t_max, *(jumps",
"boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1,",
"function, x_range=None, **kwargs): digest_config(self, kwargs) self.function = function if x_range",
"if x_range is not None: self.x_range[:len(x_range)] = x_range def parametric_function(t):",
"CONFIG = { \"t_range\": [0, 1, 0.1], \"min_samples\": 10, \"epsilon\":",
"\"discontinuities\": [], \"smoothing\": True, } def __init__(self, t_func, t_range=None, **kwargs):",
"digest_config(self, kwargs) if t_range is not None: self.t_range[:len(t_range)] = t_range",
"__init__(self, t_func, t_range=None, **kwargs): digest_config(self, kwargs) if t_range is not",
"manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject): CONFIG = { \"t_range\": [0,",
"} def __init__(self, t_func, t_range=None, **kwargs): digest_config(self, kwargs) if t_range",
"t_max)] boundary_times = [t_min, t_max, *(jumps - self.epsilon), *(jumps +",
"be backward compatible with all the scenes specifying t_min, t_max,",
"= [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func",
"jumps[(jumps > t_min) & (jumps < t_max)] boundary_times = [t_min,",
"kwargs) self.function = function if x_range is not None: self.x_range[:len(x_range)]",
"= x_range def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range,",
"self.t_func = t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self, t): return self.t_func(t)",
"*(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1, t2",
"boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t)",
"None: self.x_range[:len(x_range)] = x_range def parametric_function(t): return [t, function(t), 0]",
"def get_point_from_function(self, t): return self.t_func(t) def init_points(self): t_min, t_max, step",
"[*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t) for t in",
"t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self, t): return self.t_func(t) def init_points(self):",
"= { \"color\": YELLOW, \"x_range\": [-8, 8, 0.25], } def",
"VMobject.__init__(self, **kwargs) def get_point_from_function(self, t): return self.t_func(t) def init_points(self): t_min,",
"all the scenes specifying t_min, t_max, step_size self.t_range = [",
"from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops",
"jumps = np.array(self.discontinuities) jumps = jumps[(jumps > t_min) & (jumps",
"# To be backward compatible with all the scenes specifying",
"function if x_range is not None: self.x_range[:len(x_range)] = x_range def",
"= t_range # To be backward compatible with all the",
"return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self): return",
"manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject): CONFIG",
"digest_config from manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject): CONFIG = {",
"= self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps > t_min)",
"t_max, step_size self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\",",
"self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func = t_func VMobject.__init__(self, **kwargs) def",
"t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return self",
"jumps = jumps[(jumps > t_min) & (jumps < t_max)] boundary_times",
"__init__(self, function, x_range=None, **kwargs): digest_config(self, kwargs) self.function = function if",
"np.array(self.discontinuities) jumps = jumps[(jumps > t_min) & (jumps < t_max)]",
"\"color\": YELLOW, \"x_range\": [-8, 8, 0.25], } def __init__(self, function,",
"import * from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops import digest_config",
"x_range=None, **kwargs): digest_config(self, kwargs) self.function = function if x_range is",
"t_range # To be backward compatible with all the scenes",
"get_point_from_function(self, t): return self.t_func(t) def init_points(self): t_min, t_max, step =",
"t_range = [*np.arange(t1, t2, step), t2] points = np.array([self.t_func(t) for",
"if t_range is not None: self.t_range[:len(t_range)] = t_range # To",
"import VMobject from manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops import get_norm",
"scenes specifying t_min, t_max, step_size self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]),",
"figure out discontinuities \"discontinuities\": [], \"smoothing\": True, } def __init__(self,",
"np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth()",
"def __init__(self, t_func, t_range=None, **kwargs): digest_config(self, kwargs) if t_range is",
"\"min_samples\": 10, \"epsilon\": 1e-8, # TODO, automatically figure out discontinuities",
"specifying t_min, t_max, step_size self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\",",
"1e-8, # TODO, automatically figure out discontinuities \"discontinuities\": [], \"smoothing\":",
"= jumps[(jumps > t_min) & (jumps < t_max)] boundary_times =",
"8, 0.25], } def __init__(self, function, x_range=None, **kwargs): digest_config(self, kwargs)",
"def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) def",
"0.1], \"min_samples\": 10, \"epsilon\": 1e-8, # TODO, automatically figure out",
"def init_points(self): t_min, t_max, step = self.t_range jumps = np.array(self.discontinuities)",
"ParametricCurve(VMobject): CONFIG = { \"t_range\": [0, 1, 0.1], \"min_samples\": 10,",
"To be backward compatible with all the scenes specifying t_min,",
"get_norm class ParametricCurve(VMobject): CONFIG = { \"t_range\": [0, 1, 0.1],",
"not None: self.t_range[:len(t_range)] = t_range # To be backward compatible",
"from manimlib.utils.space_ops import get_norm class ParametricCurve(VMobject): CONFIG = { \"t_range\":",
"digest_config(self, kwargs) self.function = function if x_range is not None:",
"- self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1, t2 in",
"t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range = [*np.arange(t1, t2, step), t2]",
"t): return self.t_func(t) def init_points(self): t_min, t_max, step = self.t_range",
"self.smoothing: self.make_smooth() return self class FunctionGraph(ParametricCurve): CONFIG = { \"color\":",
"**kwargs): digest_config(self, kwargs) self.function = function if x_range is not",
"# TODO, automatically figure out discontinuities \"discontinuities\": [], \"smoothing\": True,",
"step = self.t_range jumps = np.array(self.discontinuities) jumps = jumps[(jumps >",
"self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return self class FunctionGraph(ParametricCurve): CONFIG =",
"self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2],",
"t_func, t_range=None, **kwargs): digest_config(self, kwargs) if t_range is not None:",
"kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func = t_func",
"x_range is not None: self.x_range[:len(x_range)] = x_range def parametric_function(t): return",
"[t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self): return self.function",
"\"epsilon\": 1e-8, # TODO, automatically figure out discontinuities \"discontinuities\": [],",
"10, \"epsilon\": 1e-8, # TODO, automatically figure out discontinuities \"discontinuities\":",
"{ \"color\": YELLOW, \"x_range\": [-8, 8, 0.25], } def __init__(self,",
"\"x_range\": [-8, 8, 0.25], } def __init__(self, function, x_range=None, **kwargs):",
"self.t_func(t) def init_points(self): t_min, t_max, step = self.t_range jumps =",
"t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for t1,",
"def __init__(self, function, x_range=None, **kwargs): digest_config(self, kwargs) self.function = function",
"0.25], } def __init__(self, function, x_range=None, **kwargs): digest_config(self, kwargs) self.function",
"[ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func =",
"\"smoothing\": True, } def __init__(self, t_func, t_range=None, **kwargs): digest_config(self, kwargs)",
"points = np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if",
"self.make_smooth() return self class FunctionGraph(ParametricCurve): CONFIG = { \"color\": YELLOW,",
"None: self.t_range[:len(t_range)] = t_range # To be backward compatible with",
"t_range=None, **kwargs): digest_config(self, kwargs) if t_range is not None: self.t_range[:len(t_range)]",
"super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self): return self.function def get_point_from_function(self, x):",
"x_range def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs)",
"if self.smoothing: self.make_smooth() return self class FunctionGraph(ParametricCurve): CONFIG = {",
"True, } def __init__(self, t_func, t_range=None, **kwargs): digest_config(self, kwargs) if",
"= np.array(self.discontinuities) jumps = jumps[(jumps > t_min) & (jumps <",
"compatible with all the scenes specifying t_min, t_max, step_size self.t_range",
"the scenes specifying t_min, t_max, step_size self.t_range = [ kwargs.get(\"t_min\",",
"t2, step), t2] points = np.array([self.t_func(t) for t in t_range])",
"TODO, automatically figure out discontinuities \"discontinuities\": [], \"smoothing\": True, }",
"**kwargs) def get_point_from_function(self, t): return self.t_func(t) def init_points(self): t_min, t_max,",
"is not None: self.t_range[:len(t_range)] = t_range # To be backward",
"t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return self class FunctionGraph(ParametricCurve):",
"class ParametricCurve(VMobject): CONFIG = { \"t_range\": [0, 1, 0.1], \"min_samples\":",
"out discontinuities \"discontinuities\": [], \"smoothing\": True, } def __init__(self, t_func,",
"import get_norm class ParametricCurve(VMobject): CONFIG = { \"t_range\": [0, 1,",
"VMobject from manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops import get_norm class",
"> t_min) & (jumps < t_max)] boundary_times = [t_min, t_max,",
"with all the scenes specifying t_min, t_max, step_size self.t_range =",
"< t_max)] boundary_times = [t_min, t_max, *(jumps - self.epsilon), *(jumps",
"*(jumps + self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]):",
"= np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing:",
"is not None: self.x_range[:len(x_range)] = x_range def parametric_function(t): return [t,",
"self.function = function if x_range is not None: self.x_range[:len(x_range)] =",
"parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self):",
"discontinuities \"discontinuities\": [], \"smoothing\": True, } def __init__(self, t_func, t_range=None,",
"self.x_range, **kwargs) def get_function(self): return self.function def get_point_from_function(self, x): return",
"} def __init__(self, function, x_range=None, **kwargs): digest_config(self, kwargs) self.function =",
"manimlib.constants import * from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops import",
"t_range is not None: self.t_range[:len(t_range)] = t_range # To be",
"[-8, 8, 0.25], } def __init__(self, function, x_range=None, **kwargs): digest_config(self,",
"manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops import digest_config from manimlib.utils.space_ops import",
"self.t_range[:len(t_range)] = t_range # To be backward compatible with all",
"[t_min, t_max, *(jumps - self.epsilon), *(jumps + self.epsilon)] boundary_times.sort() for",
"= t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self, t): return self.t_func(t) def",
"self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return self class FunctionGraph(ParametricCurve): CONFIG",
"self.x_range[:len(x_range)] = x_range def parametric_function(t): return [t, function(t), 0] super().__init__(parametric_function,",
"* from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops import digest_config from",
"& (jumps < t_max)] boundary_times = [t_min, t_max, *(jumps -",
"+ self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range",
"[0, 1, 0.1], \"min_samples\": 10, \"epsilon\": 1e-8, # TODO, automatically",
"step), t2] points = np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0])",
"t_min, t_max, step_size self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]),",
"self.t_range[2]), ] self.t_func = t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self, t):",
"<reponame>parmentelat/manim<gh_stars>1-10 from manimlib.constants import * from manimlib.mobject.types.vectorized_mobject import VMobject from",
"= function if x_range is not None: self.x_range[:len(x_range)] = x_range",
"**kwargs): digest_config(self, kwargs) if t_range is not None: self.t_range[:len(t_range)] =",
"automatically figure out discontinuities \"discontinuities\": [], \"smoothing\": True, } def",
"from manimlib.constants import * from manimlib.mobject.types.vectorized_mobject import VMobject from manimlib.utils.config_ops",
"self.epsilon)] boundary_times.sort() for t1, t2 in zip(boundary_times[0::2], boundary_times[1::2]): t_range =",
"not None: self.x_range[:len(x_range)] = x_range def parametric_function(t): return [t, function(t),",
"step_size self.t_range = [ kwargs.get(\"t_min\", self.t_range[0]), kwargs.get(\"t_max\", self.t_range[1]), kwargs.get(\"step_size\", self.t_range[2]),",
"for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:]) if self.smoothing: self.make_smooth() return",
"kwargs.get(\"step_size\", self.t_range[2]), ] self.t_func = t_func VMobject.__init__(self, **kwargs) def get_point_from_function(self,",
"1, 0.1], \"min_samples\": 10, \"epsilon\": 1e-8, # TODO, automatically figure",
"class FunctionGraph(ParametricCurve): CONFIG = { \"color\": YELLOW, \"x_range\": [-8, 8,",
"YELLOW, \"x_range\": [-8, 8, 0.25], } def __init__(self, function, x_range=None,",
"\"t_range\": [0, 1, 0.1], \"min_samples\": 10, \"epsilon\": 1e-8, # TODO,",
"= { \"t_range\": [0, 1, 0.1], \"min_samples\": 10, \"epsilon\": 1e-8,",
"self class FunctionGraph(ParametricCurve): CONFIG = { \"color\": YELLOW, \"x_range\": [-8,",
"t2] points = np.array([self.t_func(t) for t in t_range]) self.start_new_path(points[0]) self.add_points_as_corners(points[1:])",
"function(t), 0] super().__init__(parametric_function, self.x_range, **kwargs) def get_function(self): return self.function def",
"[], \"smoothing\": True, } def __init__(self, t_func, t_range=None, **kwargs): digest_config(self,"
] |
[
"# The full license can be found in 'LICENSE.txt'. \"\"\"ECS",
"params = self._make_params(locals()) return self._execute(params) def DeleteInstance(self, InstanceName): params =",
"{ 'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp':",
"def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params)",
"InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def ResetInstance(self, InstanceName,",
"return self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None): params = self._make_params(locals()) return",
"IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params = self._make_params(locals()) return",
"[] for k, v in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v)))",
"self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params = self._make_params(locals())",
"self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params = self._make_params(locals()) return",
"RegionCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def AllocateAddress(self,",
"SnapshotCode): params = self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode):",
"self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals())",
"def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def",
"IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params = self._make_params(locals())",
"%s\\n' % zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print",
"print '## Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions) print for region",
"str(v)) for k, v in params.items() if k != 'self'",
"= self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType): params =",
"_urlencode(self, string): return urllib.quote(string, '~') def _sign(self, params): paramstrings =",
"params = self._make_params(locals()) return self._execute(params) def AllocateAddress(self, InstanceName): params =",
"= respdata['RequestID'] del respdata['RequestID'] return [False, respdata, reqid] else: respdata",
"Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions) print for region in regions['Regions']:",
"'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams) params['Signature']",
"pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret = ''",
"return self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params = self._make_params(locals())",
"self._make_params(locals()) return self._execute(params) def DeleteInstance(self, InstanceName): params = self._make_params(locals()) return",
"Copyright (c) 2012, ECSMate development team # All rights reserved.",
"response): if response.has_key('Error'): respdata = response['Error'] reqid = respdata['RequestID'] del",
"params.items() if k != 'self' and v != None) params['Action']",
"for region in regions['Regions']: print '## Zones in %s\\n' %",
"= self._http_get(params) return self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode, DiskSize, InstanceType,",
"params = self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params",
"self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params =",
"def DescribeSnapshots(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def",
"print for zone in zones['Zones']: print '## Instances in %s\\n'",
"2012, ECSMate development team # All rights reserved. # #",
"return self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode): params = self._make_params(locals()) return",
"params = self._make_params(locals()) return self._execute(params) def ModifyHostName(self, InstanceName, HostName): params",
"self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None,",
"gateway @classmethod def _urlencode(self, string): return urllib.quote(string, '~') def _sign(self,",
"= urllib.urlencode(params) url += params f = urllib.urlopen(url) data =",
"self._execute(params) def DescribeDisks(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def",
"params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None):",
"_parse_response(self, apiname, response): if response.has_key('Error'): respdata = response['Error'] reqid =",
"GroupCode, RegionCode, NicType=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self,",
"= self._make_params(locals()) return self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode): params =",
"urllib.urlopen(url) data = f.read() f.close() return json.loads(data) def _parse_response(self, apiname,",
"params = dict((k, str(v)) for k, v in params.items() if",
"self.gateway = gateway @classmethod def _urlencode(self, string): return urllib.quote(string, '~')",
"params = self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode):",
"self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params =",
"pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221'))",
"coding: utf-8 -*- # # Copyright (c) 2012, ECSMate development",
"pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret = '' ecs = ECS(AccessKeyID,",
"self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None,",
"return self._execute(params) def DeleteInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params)",
"import time import hmac import base64 import hashlib import urllib",
"self._execute(params) def DescribeZones(self, RegionCode): params = self._make_params(locals()) return self._execute(params) if",
"reqid] else: respdata = response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def",
"Size, SnapshotCode=None): params = self._make_params(locals()) return self._execute(params) def DeleteDisk(self, InstanceName,",
"= self.gateway + '/?' sysparams = { 'Format': 'JSON', 'Version':",
"response = self._http_get(params) return self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode, DiskSize,",
"return self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return",
"} params.update(sysparams) params['Signature'] = self._sign(params) params = urllib.urlencode(params) url +=",
"def DescribeZones(self, RegionCode): params = self._make_params(locals()) return self._execute(params) if __name__",
"GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params =",
"#-*- coding: utf-8 -*- # # Copyright (c) 2012, ECSMate",
"zones = ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones) continue zones =",
"GroupCode, Adjust): params = self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self, GroupCode,",
"def CreateDisk(self, InstanceName, Size, SnapshotCode=None): params = self._make_params(locals()) return self._execute(params)",
"PublicIpAddress): params = self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode,",
"StartInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def StopInstance(self, InstanceName,",
"RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params = self._make_params(locals())",
"DescribeZones(self, RegionCode): params = self._make_params(locals()) return self._execute(params) if __name__ ==",
"ECS(object): def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret",
"= self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params",
"terms of the (new) BSD License. # The full license",
"+ '/?' sysparams = { 'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID':",
"InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None,",
"ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params = self._make_params(locals()) return self._execute(params) def",
"return self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params = self._make_params(locals()) return",
"zones = zones[1] pp.pprint(zones) print for zone in zones['Zones']: print",
"GroupCode, RegionCode): params = self._make_params(locals()) return self._execute(params) def CreateSnapshot(self, InstanceName,",
"DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None):",
"return urllib.quote(string, '~') def _sign(self, params): paramstrings = [] for",
"def ModifyInstanceAttribute(self, InstanceName, InstanceType): params = self._make_params(locals()) return self._execute(params) def",
"= self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode): params =",
"in %s\\n' % zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print",
"del respdata['RequestID'] return [False, respdata, reqid] else: respdata = response[apiname+'Response']",
"InstanceName, MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals()) return self._execute(params) def ModifyHostName(self,",
"DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def",
"self._execute(params) def StartInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def",
"self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''),",
"InstanceName): params = self._make_params(locals()) return self._execute(params) def StopInstance(self, InstanceName, ForceStop=None):",
"InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self, InstanceName,",
"InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def RebootInstance(self, InstanceName,",
"MaxBandwidthIn): params = self._make_params(locals()) return self._execute(params) def ModifyHostName(self, InstanceName, HostName):",
"= self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode, Description): params",
"return self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode, Description): params = self._make_params(locals())",
"found in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import time import hmac",
"RegionCode): params = self._make_params(locals()) return self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode):",
"<gh_stars>0 #-*- coding: utf-8 -*- # # Copyright (c) 2012,",
"ForceStop=None): params = self._make_params(locals()) return self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None,",
"for zone in zones['Zones']: print '## Instances in %s\\n' %",
"zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221'))",
"hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self, params): url =",
"Policy=None, NicType=None, Priority=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self,",
"self._make_params(locals()) return self._execute(params) def ModifyHostName(self, InstanceName, HostName): params = self._make_params(locals())",
"'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams)",
"InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals()) return self._execute(params) def",
"PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self, InstanceName):",
"PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params = self._make_params(locals()) return self._execute(params)",
"def CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None,",
"= self._make_params(locals()) return self._execute(params) def AllocateAddress(self, InstanceName): params = self._make_params(locals())",
"= self._make_params(locals()) return self._execute(params) def DescribeZones(self, RegionCode): params = self._make_params(locals())",
"SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params = self._make_params(locals()) return self._execute(params) def",
"def _urlencode(self, string): return urllib.quote(string, '~') def _sign(self, params): paramstrings",
"= self._make_params(locals()) return self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None): params =",
"ModifyHostName(self, InstanceName, HostName): params = self._make_params(locals()) return self._execute(params) def CreateDisk(self,",
"ZoneCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self,",
"params = self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode, Description):",
"in regions['Regions']: print '## Zones in %s\\n' % region['RegionCode'] zones",
"def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params = self._make_params(locals()) return self._execute(params)",
"self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params = self._make_params(locals())",
"datastring = '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature)",
"self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params =",
"DeleteSecurityGroup(self, GroupCode, RegionCode): params = self._make_params(locals()) return self._execute(params) def CreateSnapshot(self,",
"self._make_params(locals()) return self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals())",
"self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode): params = self._make_params(locals())",
"'' ecs = ECS(AccessKeyID, AccessKeySecret) if 0: print '## Regions\\n'",
"# # Copyright (c) 2012, ECSMate development team # All",
"self._execute(params) def CreateDisk(self, InstanceName, Size, SnapshotCode=None): params = self._make_params(locals()) return",
"self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params =",
"_execute(self, params): response = self._http_get(params) return self._parse_response(params['Action'], response) def CreateInstance(self,",
"params = self._make_params(locals()) return self._execute(params) def StartInstance(self, InstanceName): params =",
"AccessKeyID = '' AccessKeySecret = '' ecs = ECS(AccessKeyID, AccessKeySecret)",
"f.read() f.close() return json.loads(data) def _parse_response(self, apiname, response): if response.has_key('Error'):",
"url = self.gateway + '/?' sysparams = { 'Format': 'JSON',",
"self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType): params = self._make_params(locals())",
"respdata = response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params):",
"self._make_params(locals()) return self._execute(params) def StartInstance(self, InstanceName): params = self._make_params(locals()) return",
"params = self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None,",
"team # All rights reserved. # # ECSMate is distributed",
"DiskCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeRegions(self): params",
"== '__main__': import pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID = ''",
"params): url = self.gateway + '/?' sysparams = { 'Format':",
"params = self._make_params(locals()) return self._execute(params) def StopInstance(self, InstanceName, ForceStop=None): params",
"params = self._make_params(locals()) return self._execute(params) def DescribeRegions(self): params = self._make_params(locals())",
"self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params)",
"StopInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def RebootInstance(self,",
"SnapshotCode=None): params = self._make_params(locals()) return self._execute(params) def DeleteDisk(self, InstanceName, DiskCode):",
"return json.loads(data) def _parse_response(self, apiname, response): if response.has_key('Error'): respdata =",
"response.has_key('Error'): respdata = response['Error'] reqid = respdata['RequestID'] del respdata['RequestID'] return",
"return self._execute(params) def ModifyHostName(self, InstanceName, HostName): params = self._make_params(locals()) return",
"PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params = self._make_params(locals()) return",
"SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params = self._make_params(locals()) return self._execute(params)",
"= '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature) def",
"'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion':",
"params['Action'] = inspect.stack()[1][3] return params def _execute(self, params): response =",
"region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones) continue zones",
"__name__ == '__main__': import pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID =",
"def ModifyHostName(self, InstanceName, HostName): params = self._make_params(locals()) return self._execute(params) def",
"params f = urllib.urlopen(url) data = f.read() f.close() return json.loads(data)",
"PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode,",
"def ResetPassword(self, InstanceName, NewPassword=None): params = self._make_params(locals()) return self._execute(params) def",
"'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0',",
"from random import random class ECS(object): def __init__(self, AccessKeyID, AccessKeySecret,",
"def RebootInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def",
"RegionCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self, InstanceName,",
"DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def",
"\"\"\"ECS SDK \"\"\" import time import hmac import base64 import",
"HostName=None, Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals()) return self._execute(params) def StartInstance(self,",
"def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params = self._make_params(locals()) return self._execute(params)",
"return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params =",
"response) def CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None,",
"urllib.quote(string, '~') def _sign(self, params): paramstrings = [] for k,",
"def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params = self._make_params(locals()) return self._execute(params)",
"AccessKeySecret = '' ecs = ECS(AccessKeyID, AccessKeySecret) if 0: print",
"return self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode): params = self._make_params(locals()) return",
"RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params =",
"MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals()) return",
"self._make_params(locals()) return self._execute(params) def ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals()) return",
"def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret =",
"AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway = gateway @classmethod def _urlencode(self,",
"import random class ECS(object): def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID",
"DiskType=None): params = self._make_params(locals()) return self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None):",
"params = self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType): params",
"def StartInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def StopInstance(self,",
"return self._execute(params) def DescribeRegions(self): params = self._make_params(locals()) return self._execute(params) def",
"0: print '## Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions) print for",
"RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def",
"if not zones[0]: pp.pprint(zones) continue zones = zones[1] pp.pprint(zones) print",
"paramstrings = [] for k, v in sorted(params.items()): paramstrings.append('%s=%s' %",
"return self._execute(params) if __name__ == '__main__': import pprint pp =",
"% zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10,",
"ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self, GroupCode,",
"'2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce':",
"self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params = self._make_params(locals()) return",
"self._execute(params) def ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals()) return self._execute(params) def",
"RegionCode): params = self._make_params(locals()) return self._execute(params) if __name__ == '__main__':",
"PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221')) #pp.pprint(ecs.DescribeImages(PageSize=10, PageNumber=9)) #pp.pprint(ecs.DescribeDisks('AY1209220917063704221'))",
"license can be found in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import",
"params.update(sysparams) params['Signature'] = self._sign(params) params = urllib.urlencode(params) url += params",
"in params.items() if k != 'self' and v != None)",
"= self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params =",
"return self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode, ImageCode,",
"= ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a'))",
"import json import inspect from random import random class ECS(object):",
"params = self._make_params(locals()) return self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode): params",
"return [False, respdata, reqid] else: respdata = response[apiname+'Response'] return [True,",
"ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params = self._make_params(locals()) return self._execute(params) def",
"Instances in %s\\n' % zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances)",
"return self._execute(params) def AllocateAddress(self, InstanceName): params = self._make_params(locals()) return self._execute(params)",
"base64 import hashlib import urllib import json import inspect from",
"self._execute(params) if __name__ == '__main__': import pprint pp = pprint.PrettyPrinter(indent=4)",
"in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'),",
"RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def",
"the terms of the (new) BSD License. # The full",
"params = self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode):",
"params = self._make_params(locals()) return self._execute(params) def DescribeZones(self, RegionCode): params =",
"self._make_params(locals()) return self._execute(params) def AllocateAddress(self, InstanceName): params = self._make_params(locals()) return",
"self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params)",
"DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params)",
"= self._make_params(locals()) return self._execute(params) if __name__ == '__main__': import pprint",
"# # ECSMate is distributed under the terms of the",
"self._execute(params) def DeleteDisk(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params)",
"self._execute(params) def DescribeRegions(self): params = self._make_params(locals()) return self._execute(params) def DescribeZones(self,",
"InstanceName, HostName): params = self._make_params(locals()) return self._execute(params) def CreateDisk(self, InstanceName,",
"string): return urllib.quote(string, '~') def _sign(self, params): paramstrings = []",
"InstanceName, Size, SnapshotCode=None): params = self._make_params(locals()) return self._execute(params) def DeleteDisk(self,",
"def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return",
"AccessKeySecret) if 0: print '## Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions)",
"params = self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params",
"= self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params",
"respdata['RequestID'] return [False, respdata, reqid] else: respdata = response[apiname+'Response'] return",
"self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params = self._make_params(locals()) return",
"Zones in %s\\n' % region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if not",
"time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams) params['Signature'] =",
"and v != None) params['Action'] = inspect.stack()[1][3] return params def",
"= self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode): params =",
"InstanceName, InstanceType): params = self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self, InstanceName,",
"DescribeDisks(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeImages(self, RegionCode=None,",
"InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self, DiskCode,",
"'## Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions) print for region in",
"params = self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol,",
"'/?' sysparams = { 'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID,",
"ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals()) return self._execute(params) def",
"'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import time import hmac import base64",
"= dict((k, str(v)) for k, v in params.items() if k",
"_http_get(self, params): url = self.gateway + '/?' sysparams = {",
"= self._make_params(locals()) return self._execute(params) def ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals())",
"params): params = dict((k, str(v)) for k, v in params.items()",
"zones[1] pp.pprint(zones) print for zone in zones['Zones']: print '## Instances",
"PageSize=None): params = self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode,",
"# All rights reserved. # # ECSMate is distributed under",
"params = self._make_params(locals()) return self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None):",
"return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None,",
"be found in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import time import",
"params = urllib.urlencode(params) url += params f = urllib.urlopen(url) data",
"params = self._make_params(locals()) return self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None): params",
"DiskCode, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def CancelSnapshotRequest(self,",
"return self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None,",
"-*- # # Copyright (c) 2012, ECSMate development team #",
"rights reserved. # # ECSMate is distributed under the terms",
"'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.',",
"random class ECS(object): def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID =",
"response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params =",
"DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def",
"def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params)",
"self._make_params(locals()) return self._execute(params) def DescribeZones(self, RegionCode): params = self._make_params(locals()) return",
"urllib import json import inspect from random import random class",
"= response['Error'] reqid = respdata['RequestID'] del respdata['RequestID'] return [False, respdata,",
"ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring =",
"apiname, response): if response.has_key('Error'): respdata = response['Error'] reqid = respdata['RequestID']",
"Description): params = self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode,",
"= self._make_params(locals()) return self._execute(params) def StartInstance(self, InstanceName): params = self._make_params(locals())",
"DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self, InstanceName,",
"= self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange,",
"return params def _execute(self, params): response = self._http_get(params) return self._parse_response(params['Action'],",
"str(random()).replace('0.', ''), } params.update(sysparams) params['Signature'] = self._sign(params) params = urllib.urlencode(params)",
"sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'),",
"pp = pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret = '' ecs",
"PageSize=None): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params",
"The full license can be found in 'LICENSE.txt'. \"\"\"ECS SDK",
"= { 'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1',",
"if k != 'self' and v != None) params['Action'] =",
"= AccessKeySecret self.gateway = gateway @classmethod def _urlencode(self, string): return",
"params = self._make_params(locals()) return self._execute(params) def CreateDisk(self, InstanceName, Size, SnapshotCode=None):",
"if __name__ == '__main__': import pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID",
"return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params = dict((k,",
"= gateway @classmethod def _urlencode(self, string): return urllib.quote(string, '~') def",
"def CreateSecurityGroup(self, GroupCode, RegionCode, Description): params = self._make_params(locals()) return self._execute(params)",
"f.close() return json.loads(data) def _parse_response(self, apiname, response): if response.has_key('Error'): respdata",
"'1.0', 'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams) params['Signature'] = self._sign(params) params",
"def _parse_response(self, apiname, response): if response.has_key('Error'): respdata = response['Error'] reqid",
"k, v in params.items() if k != 'self' and v",
"!= None) params['Action'] = inspect.stack()[1][3] return params def _execute(self, params):",
"#pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221')) #pp.pprint(ecs.DescribeImages(PageSize=10, PageNumber=9)) #pp.pprint(ecs.DescribeDisks('AY1209220917063704221')) #pp.pprint(ecs.DescribeSnapshots('AY1209220917063704221',",
"def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None):",
"RebootInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def ResetInstance(self,",
"time import hmac import base64 import hashlib import urllib import",
"= response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params",
"hashlib import urllib import json import inspect from random import",
"development team # All rights reserved. # # ECSMate is",
"self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode, Description): params =",
"continue zones = zones[1] pp.pprint(zones) print for zone in zones['Zones']:",
"'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'), 'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''), }",
"import base64 import hashlib import urllib import json import inspect",
"!= 'self' and v != None) params['Action'] = inspect.stack()[1][3] return",
"= inspect.stack()[1][3] return params def _execute(self, params): response = self._http_get(params)",
"AccessKeySecret self.gateway = gateway @classmethod def _urlencode(self, string): return urllib.quote(string,",
"'self' and v != None) params['Action'] = inspect.stack()[1][3] return params",
"def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params)",
"return self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals())",
"return self._execute(params) def StartInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params)",
"RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params",
"AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None):",
"return self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals())",
"zones['Zones']: print '## Instances in %s\\n' % zone['ZoneCode'] instances =",
"print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221'))",
"= ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones) continue zones = zones[1]",
"self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None): params = self._make_params(locals()) return self._execute(params)",
"[ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings) signature =",
"ecs.DescribeRegions()[1] pp.pprint(regions) print for region in regions['Regions']: print '## Zones",
"RegionCode, PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self,",
"return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params = self._make_params(locals()) return",
"print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221')) #pp.pprint(ecs.DescribeImages(PageSize=10,",
"def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None,",
"self._execute(params) def StopInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params)",
"ImageCode=None, DiskType=None): params = self._make_params(locals()) return self._execute(params) def ResetPassword(self, InstanceName,",
"v != None) params['Action'] = inspect.stack()[1][3] return params def _execute(self,",
"pp.pprint(zones) continue zones = zones[1] pp.pprint(zones) print for zone in",
"%s\\n' % region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones)",
"print '## Instances in %s\\n' % zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'],",
"MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals()) return self._execute(params)",
"MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals()) return self._execute(params) def ModifyHostName(self, InstanceName,",
"region in regions['Regions']: print '## Zones in %s\\n' % region['RegionCode']",
"__init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret = AccessKeySecret",
"= self._make_params(locals()) return self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params",
"'' AccessKeySecret = '' ecs = ECS(AccessKeyID, AccessKeySecret) if 0:",
"return self._execute(params) def ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals()) return self._execute(params)",
"InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self, InstanceName,",
"can be found in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import time",
"regions = ecs.DescribeRegions()[1] pp.pprint(regions) print for region in regions['Regions']: print",
"hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self, params): url = self.gateway +",
"'SignatureVersion': '1.0', 'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams) params['Signature'] = self._sign(params)",
"RegionCode, NicType=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self, RegionCode,",
"def DescribeRegions(self): params = self._make_params(locals()) return self._execute(params) def DescribeZones(self, RegionCode):",
"'SignatureNonce': str(random()).replace('0.', ''), } params.update(sysparams) params['Signature'] = self._sign(params) params =",
"CancelSnapshotRequest(self, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self,",
"params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None):",
"= self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params",
"# Copyright (c) 2012, ECSMate development team # All rights",
"= '' AccessKeySecret = '' ecs = ECS(AccessKeyID, AccessKeySecret) if",
"distributed under the terms of the (new) BSD License. #",
"= self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params =",
"InstanceType): params = self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut,",
"respdata['RequestID'] del respdata['RequestID'] return [False, respdata, reqid] else: respdata =",
"self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params = self._make_params(locals()) return",
"k, v in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings =",
"zones[0]: pp.pprint(zones) continue zones = zones[1] pp.pprint(zones) print for zone",
"self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode): params = self._make_params(locals()) return self._execute(params)",
"'__main__': import pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret",
"def _sign(self, params): paramstrings = [] for k, v in",
"self._make_params(locals()) return self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params =",
"in %s\\n' % region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if not zones[0]:",
"k != 'self' and v != None) params['Action'] = inspect.stack()[1][3]",
"ZoneCode=None): params = self._make_params(locals()) return self._execute(params) def StartInstance(self, InstanceName): params",
"PageNumber=None, PageSize=None): params = self._make_params(locals()) return self._execute(params) def AllocateAddress(self, InstanceName):",
"def ReleaseAddress(self, PublicIpAddress): params = self._make_params(locals()) return self._execute(params) def CreateSecurityGroup(self,",
"'## Instances in %s\\n' % zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1]",
"random import random class ECS(object): def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'):",
"self._make_params(locals()) return self._execute(params) def StopInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals())",
"def DeleteInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self,",
"= pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret = '' ecs =",
"def DeleteSecurityGroup(self, GroupCode, RegionCode): params = self._make_params(locals()) return self._execute(params) def",
"return self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params = self._make_params(locals())",
"= self._make_params(locals()) return self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None): params =",
"ForceStop=None): params = self._make_params(locals()) return self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None):",
"self._execute(params) def CreateSecurityGroup(self, GroupCode, RegionCode, Description): params = self._make_params(locals()) return",
"in zones['Zones']: print '## Instances in %s\\n' % zone['ZoneCode'] instances",
"of the (new) BSD License. # The full license can",
"SDK \"\"\" import time import hmac import base64 import hashlib",
"def DescribeDisks(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeImages(self,",
"return self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType): params = self._make_params(locals()) return",
"GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None, Priority=None): params",
"InstanceName, ImageCode=None, DiskType=None): params = self._make_params(locals()) return self._execute(params) def ResetPassword(self,",
"DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self,",
"respdata = response['Error'] reqid = respdata['RequestID'] del respdata['RequestID'] return [False,",
"if 0: print '## Regions\\n' regions = ecs.DescribeRegions()[1] pp.pprint(regions) print",
"self._sign(params) params = urllib.urlencode(params) url += params f = urllib.urlopen(url)",
"GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params =",
"datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings)",
"self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params = self._make_params(locals()) return",
"if response.has_key('Error'): respdata = response['Error'] reqid = respdata['RequestID'] del respdata['RequestID']",
"[False, respdata, reqid] else: respdata = response[apiname+'Response'] return [True, respdata[apiname+'Result'],",
"InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params",
"signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self, params):",
"= [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings) signature",
"ECSMate development team # All rights reserved. # # ECSMate",
"params = self._make_params(locals()) return self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None):",
"SourceGroupCode=None, SourceCidrIp=None, Policy=None, NicType=None): params = self._make_params(locals()) return self._execute(params) def",
"= self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params",
"pp.pprint(regions) print for region in regions['Regions']: print '## Zones in",
"base64.b64encode(signature) def _http_get(self, params): url = self.gateway + '/?' sysparams",
"for k, v in params.items() if k != 'self' and",
"ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals())",
"SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode):",
"respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params = dict((k, str(v)) for k,",
"All rights reserved. # # ECSMate is distributed under the",
"NewPassword=None): params = self._make_params(locals()) return self._execute(params) def DeleteInstance(self, InstanceName): params",
"NicType=None, Priority=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode,",
"f = urllib.urlopen(url) data = f.read() f.close() return json.loads(data) def",
"CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None,",
"def AllocateAddress(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def ReleaseAddress(self,",
"for k, v in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings",
"self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals()) return",
"InstanceName, NewPassword=None): params = self._make_params(locals()) return self._execute(params) def DeleteInstance(self, InstanceName):",
"params = self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode): params",
"ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&',",
"= self._make_params(locals()) return self._execute(params) def ModifyHostName(self, InstanceName, HostName): params =",
"self._execute(params) def ModifyHostName(self, InstanceName, HostName): params = self._make_params(locals()) return self._execute(params)",
"= self._sign(params) params = urllib.urlencode(params) url += params f =",
"RegionCode, Description): params = self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode,",
"ECS(AccessKeyID, AccessKeySecret) if 0: print '## Regions\\n' regions = ecs.DescribeRegions()[1]",
"in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\" import time import hmac import",
"ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest()",
"self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None,",
"'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod': 'HMAC-SHA1', 'Timestamp': time.strftime('%Y-%m-%dT%XZ'),",
"AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway =",
"the (new) BSD License. # The full license can be",
"CreateSecurityGroup(self, GroupCode, RegionCode, Description): params = self._make_params(locals()) return self._execute(params) def",
"self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType): params = self._make_params(locals()) return self._execute(params)",
"params = self._make_params(locals()) return self._execute(params) def DeleteDisk(self, InstanceName, DiskCode): params",
"v in params.items() if k != 'self' and v !=",
"def _http_get(self, params): url = self.gateway + '/?' sysparams =",
"is distributed under the terms of the (new) BSD License.",
"DeleteInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None,",
"self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange, SourceGroupCode=None, SourceCidrIp=None, Policy=None,",
"_make_params(self, params): params = dict((k, str(v)) for k, v in",
"inspect.stack()[1][3] return params def _execute(self, params): response = self._http_get(params) return",
"def DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self,",
"gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway = gateway",
"reserved. # # ECSMate is distributed under the terms of",
"datastring, hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self, params): url = self.gateway",
"json import inspect from random import random class ECS(object): def",
"InstanceName, DiskCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeRegions(self):",
"= AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway = gateway @classmethod def",
"regions['Regions']: print '## Zones in %s\\n' % region['RegionCode'] zones =",
"DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params = self._make_params(locals()) return self._execute(params) def",
"else: respdata = response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self,",
"self._make_params(locals()) return self._execute(params) def DescribeDisks(self, InstanceName): params = self._make_params(locals()) return",
"return self._execute(params) def DeleteDisk(self, InstanceName, DiskCode): params = self._make_params(locals()) return",
"respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params = dict((k, str(v)) for",
"return self._execute(params) def DescribeZones(self, RegionCode): params = self._make_params(locals()) return self._execute(params)",
"[True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']] def _make_params(self, params): params = dict((k, str(v))",
"# ECSMate is distributed under the terms of the (new)",
"@classmethod def _urlencode(self, string): return urllib.quote(string, '~') def _sign(self, params):",
"pp.pprint(zones) print for zone in zones['Zones']: print '## Instances in",
"self._execute(params) def DeleteInstance(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def",
"ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring = '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring,",
"respdata, reqid] else: respdata = response[apiname+'Response'] return [True, respdata[apiname+'Result'], respdata['ResponseMetadata']['RequestID']]",
"reqid = respdata['RequestID'] del respdata['RequestID'] return [False, respdata, reqid] else:",
"Password=<PASSWORD>, ZoneCode=None): params = self._make_params(locals()) return self._execute(params) def StartInstance(self, InstanceName):",
"self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params)",
"self._make_params(locals()) return self._execute(params) def DescribeRegions(self): params = self._make_params(locals()) return self._execute(params)",
"= self._make_params(locals()) return self._execute(params) def ResetInstance(self, InstanceName, ImageCode=None, DiskType=None): params",
"self._make_params(locals()) return self._execute(params) def CreateDisk(self, InstanceName, Size, SnapshotCode=None): params =",
"RegionCode, GroupCode, Adjust): params = self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self,",
"return self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals()) return self._execute(params)",
"self.AccessKeySecret = AccessKeySecret self.gateway = gateway @classmethod def _urlencode(self, string):",
"= self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params",
"'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221')) #pp.pprint(ecs.DescribeImages(PageSize=10, PageNumber=9)) #pp.pprint(ecs.DescribeDisks('AY1209220917063704221')) #pp.pprint(ecs.DescribeSnapshots('AY1209220917063704221', '1006-60002839'))",
"None) params['Action'] = inspect.stack()[1][3] return params def _execute(self, params): response",
"InstanceName): params = self._make_params(locals()) return self._execute(params) def ModifyInstanceAttribute(self, InstanceName, InstanceType):",
"return self._execute(params) def DescribeDisks(self, InstanceName): params = self._make_params(locals()) return self._execute(params)",
"params = self._make_params(locals()) return self._execute(params) def RebootInstance(self, InstanceName, ForceStop=None): params",
"return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params = self._make_params(locals())",
"self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params =",
"= urllib.urlopen(url) data = f.read() f.close() return json.loads(data) def _parse_response(self,",
"InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeDisks(self, InstanceName):",
"(c) 2012, ECSMate development team # All rights reserved. #",
"self._make_params(locals()) return self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None, PageSize=None): params =",
"+= params f = urllib.urlopen(url) data = f.read() f.close() return",
"self._make_params(locals()) return self._execute(params) def DeleteDisk(self, InstanceName, DiskCode): params = self._make_params(locals())",
"HostName): params = self._make_params(locals()) return self._execute(params) def CreateDisk(self, InstanceName, Size,",
"= ECS(AccessKeyID, AccessKeySecret) if 0: print '## Regions\\n' regions =",
"self._make_params(locals()) return self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode): params = self._make_params(locals())",
"ecs = ECS(AccessKeyID, AccessKeySecret) if 0: print '## Regions\\n' regions",
"def DeleteDisk(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def",
"self._execute(params) def AllocateAddress(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def",
"DescribeSnapshots(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self,",
"= '' ecs = ECS(AccessKeyID, AccessKeySecret) if 0: print '##",
"return base64.b64encode(signature) def _http_get(self, params): url = self.gateway + '/?'",
"''), } params.update(sysparams) params['Signature'] = self._sign(params) params = urllib.urlencode(params) url",
"self._execute(params) def CreateSnapshot(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params)",
"hmac import base64 import hashlib import urllib import json import",
"self._http_get(params) return self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode,",
"ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones) continue zones = zones[1] pp.pprint(zones)",
"= zones[1] pp.pprint(zones) print for zone in zones['Zones']: print '##",
"NicType=None): params = self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode):",
"(new) BSD License. # The full license can be found",
"SnapshotCode): params = self._make_params(locals()) return self._execute(params) def DescribeRegions(self): params =",
"PageSize=None): params = self._make_params(locals()) return self._execute(params) def AllocateAddress(self, InstanceName): params",
"= self._make_params(locals()) return self._execute(params) def DeleteDisk(self, InstanceName, DiskCode): params =",
"ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221'))",
"def CreateSnapshot(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def",
"return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode, NicType=None): params = self._make_params(locals())",
"DiskCode): params = self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName,",
"def _make_params(self, params): params = dict((k, str(v)) for k, v",
"SourceCidrIp=None, Policy=None, NicType=None): params = self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self,",
"DeleteDisk(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeDisks(self,",
"def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals()) return self._execute(params)",
"return self._execute(params) def DeleteSecurityGroup(self, GroupCode, RegionCode): params = self._make_params(locals()) return",
"InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode,",
"RegionCode, DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None, MaxBandwidthOut=None, InstanceName=None, HostName=None, Password=<PASSWORD>,",
"self._make_params(locals()) return self._execute(params) if __name__ == '__main__': import pprint pp",
"params): paramstrings = [] for k, v in sorted(params.items()): paramstrings.append('%s=%s'",
"self._make_params(locals()) return self._execute(params) def ResetPassword(self, InstanceName, NewPassword=None): params = self._make_params(locals())",
"self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def",
"def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params) def",
"self._execute(params) def CancelSnapshotRequest(self, InstanceName, SnapshotCode): params = self._make_params(locals()) return self._execute(params)",
"NicType=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None,",
"params['Signature'] = self._sign(params) params = urllib.urlencode(params) url += params f",
"% region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if not zones[0]: pp.pprint(zones) continue",
"self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params = self._make_params(locals()) return",
"'&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self,",
"] datastring = '&'.join(datastrings) signature = hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return",
"= self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params = self._make_params(locals())",
"Policy=None, NicType=None): params = self._make_params(locals()) return self._execute(params) def DeleteSecurityGroup(self, GroupCode,",
"= self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode, IpProtocol, PortRange,",
"Priority=None): params = self._make_params(locals()) return self._execute(params) def DescribeSecurityGroupAttribute(self, GroupCode, RegionCode,",
"inspect from random import random class ECS(object): def __init__(self, AccessKeyID,",
"= self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None):",
"DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeDisks(self, InstanceName): params",
"= self._make_params(locals()) return self._execute(params) def DeleteInstance(self, InstanceName): params = self._make_params(locals())",
"BSD License. # The full license can be found in",
"ResetPassword(self, InstanceName, NewPassword=None): params = self._make_params(locals()) return self._execute(params) def DeleteInstance(self,",
"AllocateAddress(self, InstanceName): params = self._make_params(locals()) return self._execute(params) def ReleaseAddress(self, PublicIpAddress):",
"print for region in regions['Regions']: print '## Zones in %s\\n'",
"params = self._make_params(locals()) return self._execute(params) if __name__ == '__main__': import",
"sysparams = { 'Format': 'JSON', 'Version': '2012-09-13', 'AccessKeyID': self.AccessKeyID, 'SignatureMethod':",
"License. # The full license can be found in 'LICENSE.txt'.",
"params = self._make_params(locals()) return self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust):",
"url += params f = urllib.urlopen(url) data = f.read() f.close()",
"ModifyInstanceAttribute(self, InstanceName, InstanceType): params = self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self,",
"= f.read() f.close() return json.loads(data) def _parse_response(self, apiname, response): if",
"import inspect from random import random class ECS(object): def __init__(self,",
"'~') def _sign(self, params): paramstrings = [] for k, v",
"data = f.read() f.close() return json.loads(data) def _parse_response(self, apiname, response):",
"= ecs.DescribeRegions()[1] pp.pprint(regions) print for region in regions['Regions']: print '##",
"self.gateway + '/?' sysparams = { 'Format': 'JSON', 'Version': '2012-09-13',",
"params = self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode): params",
"AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway",
"self.AccessKeyID = AccessKeyID self.AccessKeySecret = AccessKeySecret self.gateway = gateway @classmethod",
"def StopInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return self._execute(params) def",
"self._make_params(locals()) return self._execute(params) def DescribeInstanceStatus(self, RegionCode=None, ZoneCode=None, PageNumber=None, PageSize=None): params",
"params = self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self, GroupCode, RegionCode, IpProtocol,",
"ECSMate is distributed under the terms of the (new) BSD",
"\"\"\" import time import hmac import base64 import hashlib import",
"dict((k, str(v)) for k, v in params.items() if k !=",
"urllib.urlencode(params) url += params f = urllib.urlopen(url) data = f.read()",
"self._make_params(locals()) return self._execute(params) def DescribeSnapshots(self, InstanceName, DiskCode): params = self._make_params(locals())",
"= [] for k, v in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k),",
"def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params = self._make_params(locals()) return self._execute(params)",
"return self._execute(params) def StopInstance(self, InstanceName, ForceStop=None): params = self._make_params(locals()) return",
"params): response = self._http_get(params) return self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode,",
"'## Zones in %s\\n' % region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode']) if",
"= self._make_params(locals()) return self._execute(params) def DescribeDisks(self, InstanceName): params = self._make_params(locals())",
"SnapshotCode): params = self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode,",
"class ECS(object): def __init__(self, AccessKeyID, AccessKeySecret, gateway='https://ecs.aliyuncs.com'): self.AccessKeyID = AccessKeyID",
"CreateDisk(self, InstanceName, Size, SnapshotCode=None): params = self._make_params(locals()) return self._execute(params) def",
"params = self._make_params(locals()) return self._execute(params) def DescribeDisks(self, InstanceName): params =",
"CreateSnapshot(self, InstanceName, DiskCode): params = self._make_params(locals()) return self._execute(params) def DeleteSnapshot(self,",
"import hmac import base64 import hashlib import urllib import json",
"InstanceName): params = self._make_params(locals()) return self._execute(params) def DescribeImages(self, RegionCode=None, PageNumber=None,",
"= self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn): params",
"#pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01', 'cn-hangzhou-dg101-a')) #pp.pprint(ecs.StartInstance('AY1209220917063704221')) #pp.pprint(ecs.StopInstance('AY1209220917063704221')) #pp.pprint(ecs.RebootInstance('AY1209220917063704221')) #pp.pprint(ecs.DescribeInstanceAttribute('AY1209220917063704221')) #pp.pprint(ecs.DescribeImages(PageSize=10, PageNumber=9))",
"return self._execute(params) def CreateDisk(self, InstanceName, Size, SnapshotCode=None): params = self._make_params(locals())",
"import hashlib import urllib import json import inspect from random",
"self._execute(params) def ModifySecurityGroupAttribute(self, RegionCode, GroupCode, Adjust): params = self._make_params(locals()) return",
"GroupCode, RegionCode, Description): params = self._make_params(locals()) return self._execute(params) def AuthorizeSecurityGroup(self,",
"not zones[0]: pp.pprint(zones) continue zones = zones[1] pp.pprint(zones) print for",
"InstanceName): params = self._make_params(locals()) return self._execute(params) def ReleaseAddress(self, PublicIpAddress): params",
"self._execute(params) def DeleteSnapshot(self, DiskCode, InstanceName, SnapshotCode): params = self._make_params(locals()) return",
"json.loads(data) def _parse_response(self, apiname, response): if response.has_key('Error'): respdata = response['Error']",
"zone['ZoneCode'] instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1))",
"utf-8 -*- # # Copyright (c) 2012, ECSMate development team",
"= self._make_params(locals()) return self._execute(params) def DescribeRegions(self): params = self._make_params(locals()) return",
"params = self._make_params(locals()) return self._execute(params) def ReleaseAddress(self, PublicIpAddress): params =",
"DescribeRegions(self): params = self._make_params(locals()) return self._execute(params) def DescribeZones(self, RegionCode): params",
"self._make_params(locals()) return self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params =",
"(ECS._urlencode(k), ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ] datastring",
"def _execute(self, params): response = self._http_get(params) return self._parse_response(params['Action'], response) def",
"return self._execute(params) def RollbackSnapshot(self, InstanceName, DiskCode, SnapshotCode): params = self._make_params(locals())",
"print '## Zones in %s\\n' % region['RegionCode'] zones = ecs.DescribeZones(region['RegionCode'])",
"import pprint pp = pprint.PrettyPrinter(indent=4) AccessKeyID = '' AccessKeySecret =",
"response['Error'] reqid = respdata['RequestID'] del respdata['RequestID'] return [False, respdata, reqid]",
"params = self._make_params(locals()) return self._execute(params) def ModifyBandwidth(self, InstanceName, MaxBandwidthOut, MaxBandwidthIn):",
"% (ECS._urlencode(k), ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)), ]",
"= hmac.new(self.AccessKeySecret+'&', datastring, hashlib.sha1).digest() return base64.b64encode(signature) def _http_get(self, params): url",
"Adjust): params = self._make_params(locals()) return self._execute(params) def RevokeSecurityGroup(self, GroupCode, RegionCode,",
"paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings = [ ECS._urlencode('GET'), ECS._urlencode('/'), ECS._urlencode('&'.join(paramstrings)),",
"v in sorted(params.items()): paramstrings.append('%s=%s' % (ECS._urlencode(k), ECS._urlencode(v))) datastrings = [",
"params = self._make_params(locals()) return self._execute(params) def DescribeInstanceAttribute(self, InstanceName): params =",
"zone in zones['Zones']: print '## Instances in %s\\n' % zone['ZoneCode']",
"import urllib import json import inspect from random import random",
"params def _execute(self, params): response = self._http_get(params) return self._parse_response(params['Action'], response)",
"_sign(self, params): paramstrings = [] for k, v in sorted(params.items()):",
"DiskCode): params = self._make_params(locals()) return self._execute(params) def DescribeSnapshotAttribute(self, RegionCode, SnapshotCode):",
"return self._execute(params) def DescribeSecurityGroups(self, RegionCode, PageNumber=None, PageSize=None): params = self._make_params(locals())",
"under the terms of the (new) BSD License. # The",
"= self._make_params(locals()) return self._execute(params) def StopInstance(self, InstanceName, ForceStop=None): params =",
"= self._make_params(locals()) return self._execute(params) def CreateDisk(self, InstanceName, Size, SnapshotCode=None): params",
"instances = ecs.DescribeInstanceStatus(region['RegionCode'], zone['ZoneCode'])[1] pp.pprint(instances) print print #pp.pprint(ecs.DescribeInstanceStatus(PageSize=10, PageNumber=1)) #pp.pprint(ecs.DescribeInstanceStatus('cn-hangzhou-dg-a01',",
"self._parse_response(params['Action'], response) def CreateInstance(self, RegionCode, DiskSize, InstanceType, GroupCode, ImageCode, MaxBandwidthIn=None,",
"full license can be found in 'LICENSE.txt'. \"\"\"ECS SDK \"\"\""
] |
[
") raise mapped_exc status = action_status.get(action, 200) body = serializer.serialize(result)",
"body = None return webob.Response(request=request, status=status, content_type=content_type, body=body) return resource",
"logging import webob.dec from tacker.api import api_common from tacker import",
"deserializers=None, serializers=None): \"\"\"API entity resource. Represents an API entity resource",
"raise mapped_exc status = action_status.get(action, 200) body = serializer.serialize(result) #",
"Copyright 2012 OpenStack Foundation. # All Rights Reserved. # #",
"def resource(request): route_args = request.environ.get('wsgiorg.routing_args') if route_args: args = route_args[1].copy()",
"serialization and deserialization logic \"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers",
"action) result = method(request=request, **args) except Exception as e: mapped_exc",
"extract_exc_details(e): for attr in ('_error_context_msg', '_error_context_args'): if not hasattr(e, attr):",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"with WSGI servers redux \"\"\" from oslo_log import log as",
"specific language governing permissions and limitations # under the License.",
"# not use this file except in compliance with the",
"{'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'}",
"= deserializers.get(content_type) serializer = serializers.get(content_type) try: if request.body: args['body'] =",
"in compliance with the License. You may obtain # a",
"associated serialization and deserialization logic \"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()}",
"= args.pop('action', None) content_type = format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language()",
"You may obtain # a copy of the License at",
"= method(request=request, **args) except Exception as e: mapped_exc = api_common.convert_exception_to_http_exc(e,",
"method = getattr(controller, action) result = method(request=request, **args) except Exception",
"entity resource. Represents an API entity resource and the associated",
"'code') and 400 <= mapped_exc.code < 500: LOG.info(_('%(action)s failed (client",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"the controller is already found, remove # it from the",
"from tacker.api import api_common from tacker import wsgi LOG =",
"resource and the associated serialization and deserialization logic \"\"\" default_deserializers",
"faults = faults or {} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args =",
"under the License is distributed on an \"AS IS\" BASIS,",
"# it from the args if it is in the",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"9.7 if status == 204: content_type = '' body =",
"this file except in compliance with the License. You may",
"route_args = request.environ.get('wsgiorg.routing_args') if route_args: args = route_args[1].copy() else: args",
"log as logging import webob.dec from tacker.api import api_common from",
"= format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language() deserializer = deserializers.get(content_type) serializer",
"action = args.pop('action', None) content_type = format_types.get(fmt, request.best_match_content_type()) language =",
"webob.Response(request=request, status=status, content_type=content_type, body=body) return resource _NO_ARGS_MARKER = object() def",
"software # distributed under the License is distributed on an",
"(the \"License\"); you may # not use this file except",
"== 204: content_type = '' body = None return webob.Response(request=request,",
"for attr in ('_error_context_msg', '_error_context_args'): if not hasattr(e, attr): return",
"{'action': action, 'exc': mapped_exc}) else: LOG.exception( _('%(action)s failed: %(details)s'), {",
"the License. \"\"\" Utility methods for working with WSGI servers",
"body=body) return resource _NO_ARGS_MARKER = object() def extract_exc_details(e): for attr",
"delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers or {}) deserializers = default_deserializers",
"controller is already found, remove # it from the args",
"None) action = args.pop('action', None) content_type = format_types.get(fmt, request.best_match_content_type()) language",
"mapped_exc status = action_status.get(action, 200) body = serializer.serialize(result) # NOTE(jkoelker)",
"= default_deserializers serializers = default_serializers faults = faults or {}",
"file except in compliance with the License. You may obtain",
"args.pop('action', None) content_type = format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language() deserializer",
"route_args[1].copy() else: args = {} # NOTE(jkoelker) by now the",
"deserializers = default_deserializers serializers = default_serializers faults = faults or",
"language) if hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code < 500:",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"the specific language governing permissions and limitations # under the",
"\"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types",
"args.pop('format', None) action = args.pop('action', None) content_type = format_types.get(fmt, request.best_match_content_type())",
"API entity resource and the associated serialization and deserialization logic",
"and the associated serialization and deserialization logic \"\"\" default_deserializers =",
"@webob.dec.wsgify(RequestClass=Request) def resource(request): route_args = request.environ.get('wsgiorg.routing_args') if route_args: args =",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"fmt = args.pop('format', None) action = args.pop('action', None) content_type =",
"the matchdict args.pop('controller', None) fmt = args.pop('format', None) action =",
"hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code < 500: LOG.info(_('%(action)s failed",
"= serializers.get(content_type) try: if request.body: args['body'] = deserializer.deserialize(request.body)['body'] method =",
"for working with WSGI servers redux \"\"\" from oslo_log import",
"= {'application/json': wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'} action_status = dict(create=201,",
"if status == 204: content_type = '' body = None",
"mapped_exc}) else: LOG.exception( _('%(action)s failed: %(details)s'), { 'action': action, 'details':",
"_('%(action)s failed: %(details)s'), { 'action': action, 'details': extract_exc_details(e), } )",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"\"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY",
"500: LOG.info(_('%(action)s failed (client error): %(exc)s'), {'action': action, 'exc': mapped_exc})",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"to in writing, software # distributed under the License is",
"or agreed to in writing, software # distributed under the",
"object() def extract_exc_details(e): for attr in ('_error_context_msg', '_error_context_args'): if not",
"required by applicable law or agreed to in writing, software",
"Apache License, Version 2.0 (the \"License\"); you may # not",
"import log as logging import webob.dec from tacker.api import api_common",
"{}) default_serializers.update(serializers or {}) deserializers = default_deserializers serializers = default_serializers",
"dict(create=201, delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers or {}) deserializers =",
"is in the matchdict args.pop('controller', None) fmt = args.pop('format', None)",
"All Rights Reserved. # # Licensed under the Apache License,",
"agreed to in writing, software # distributed under the License",
"distributed under the License is distributed on an \"AS IS\"",
"and deserialization logic \"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers =",
"request.best_match_content_type()) language = request.best_match_language() deserializer = deserializers.get(content_type) serializer = serializers.get(content_type)",
"format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language() deserializer = deserializers.get(content_type) serializer =",
"'details': extract_exc_details(e), } ) raise mapped_exc status = action_status.get(action, 200)",
"License, Version 2.0 (the \"License\"); you may # not use",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"found, remove # it from the args if it is",
"and 400 <= mapped_exc.code < 500: LOG.info(_('%(action)s failed (client error):",
"is already found, remove # it from the args if",
"not use this file except in compliance with the License.",
"writing, software # distributed under the License is distributed on",
"resource. Represents an API entity resource and the associated serialization",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"an API entity resource and the associated serialization and deserialization",
"the License. You may obtain # a copy of the",
"an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF",
"use this file except in compliance with the License. You",
"= getattr(controller, action) result = method(request=request, **args) except Exception as",
"if hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code < 500: LOG.info(_('%(action)s",
"status = action_status.get(action, 200) body = serializer.serialize(result) # NOTE(jkoelker) Comply",
"return webob.Response(request=request, status=status, content_type=content_type, body=body) return resource _NO_ARGS_MARKER = object()",
"RFC2616 section 9.7 if status == 204: content_type = ''",
"'exc': mapped_exc}) else: LOG.exception( _('%(action)s failed: %(details)s'), { 'action': action,",
"License is distributed on an \"AS IS\" BASIS, WITHOUT #",
"KIND, either express or implied. See the # License for",
"or {}) deserializers = default_deserializers serializers = default_serializers faults =",
"api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code",
"\"License\"); you may # not use this file except in",
"IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND,",
"def extract_exc_details(e): for attr in ('_error_context_msg', '_error_context_args'): if not hasattr(e,",
"express or implied. See the # License for the specific",
"None) fmt = args.pop('format', None) action = args.pop('action', None) content_type",
"and limitations # under the License. \"\"\" Utility methods for",
"the Apache License, Version 2.0 (the \"License\"); you may #",
"%(exc)s'), {'action': action, 'exc': mapped_exc}) else: LOG.exception( _('%(action)s failed: %(details)s'),",
"See the # License for the specific language governing permissions",
"Represents an API entity resource and the associated serialization and",
"logic \"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()}",
"# NOTE(jkoelker) Comply with RFC2616 section 9.7 if status ==",
"deserializer = deserializers.get(content_type) serializer = serializers.get(content_type) try: if request.body: args['body']",
"the associated serialization and deserialization logic \"\"\" default_deserializers = {'application/json':",
"with RFC2616 section 9.7 if status == 204: content_type =",
"from the args if it is in the matchdict args.pop('controller',",
"args = {} # NOTE(jkoelker) by now the controller is",
"if it is in the matchdict args.pop('controller', None) fmt =",
"# a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"serializers.get(content_type) try: if request.body: args['body'] = deserializer.deserialize(request.body)['body'] method = getattr(controller,",
"status == 204: content_type = '' body = None return",
"from tacker import wsgi LOG = logging.getLogger(__name__) class Request(wsgi.Request): pass",
"law or agreed to in writing, software # distributed under",
"limitations # under the License. \"\"\" Utility methods for working",
"content_type=content_type, body=body) return resource _NO_ARGS_MARKER = object() def extract_exc_details(e): for",
"working with WSGI servers redux \"\"\" from oslo_log import log",
"= None return webob.Response(request=request, status=status, content_type=content_type, body=body) return resource _NO_ARGS_MARKER",
"args if it is in the matchdict args.pop('controller', None) fmt",
"else: args = {} # NOTE(jkoelker) by now the controller",
"implied. See the # License for the specific language governing",
"{} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args = request.environ.get('wsgiorg.routing_args') if route_args: args",
"extract_exc_details(e), } ) raise mapped_exc status = action_status.get(action, 200) body",
"import wsgi LOG = logging.getLogger(__name__) class Request(wsgi.Request): pass def Resource(controller,",
"error): %(exc)s'), {'action': action, 'exc': mapped_exc}) else: LOG.exception( _('%(action)s failed:",
"= default_serializers faults = faults or {} @webob.dec.wsgify(RequestClass=Request) def resource(request):",
"= {} # NOTE(jkoelker) by now the controller is already",
"result = method(request=request, **args) except Exception as e: mapped_exc =",
"action, 'exc': mapped_exc}) else: LOG.exception( _('%(action)s failed: %(details)s'), { 'action':",
"failed: %(details)s'), { 'action': action, 'details': extract_exc_details(e), } ) raise",
"import api_common from tacker import wsgi LOG = logging.getLogger(__name__) class",
"attr): return _('No details.') details = e._error_context_msg args = e._error_context_args",
"default_deserializers serializers = default_serializers faults = faults or {} @webob.dec.wsgify(RequestClass=Request)",
"if not hasattr(e, attr): return _('No details.') details = e._error_context_msg",
"content_type = format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language() deserializer = deserializers.get(content_type)",
"None) content_type = format_types.get(fmt, request.best_match_content_type()) language = request.best_match_language() deserializer =",
"language governing permissions and limitations # under the License. \"\"\"",
"Utility methods for working with WSGI servers redux \"\"\" from",
"now the controller is already found, remove # it from",
"{'json': 'application/json'} action_status = dict(create=201, delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers",
"entity resource and the associated serialization and deserialization logic \"\"\"",
"the args if it is in the matchdict args.pop('controller', None)",
"<filename>tacker/api/v1/resource.py # Copyright 2012 OpenStack Foundation. # All Rights Reserved.",
"200) body = serializer.serialize(result) # NOTE(jkoelker) Comply with RFC2616 section",
"License. \"\"\" Utility methods for working with WSGI servers redux",
"language = request.best_match_language() deserializer = deserializers.get(content_type) serializer = serializers.get(content_type) try:",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR",
"**args) except Exception as e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language)",
"# # Licensed under the Apache License, Version 2.0 (the",
"by now the controller is already found, remove # it",
"webob.dec from tacker.api import api_common from tacker import wsgi LOG",
"def Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API entity resource. Represents an",
"= e._error_context_args if args is _NO_ARGS_MARKER: return details return details",
"{}) deserializers = default_deserializers serializers = default_serializers faults = faults",
"args['body'] = deserializer.deserialize(request.body)['body'] method = getattr(controller, action) result = method(request=request,",
"obtain # a copy of the License at # #",
"= action_status.get(action, 200) body = serializer.serialize(result) # NOTE(jkoelker) Comply with",
"already found, remove # it from the args if it",
"except Exception as e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language) if",
"default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'} action_status =",
"tacker import wsgi LOG = logging.getLogger(__name__) class Request(wsgi.Request): pass def",
"Version 2.0 (the \"License\"); you may # not use this",
"= {'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types = {'json':",
"'action': action, 'details': extract_exc_details(e), } ) raise mapped_exc status =",
"governing permissions and limitations # under the License. \"\"\" Utility",
"License for the specific language governing permissions and limitations #",
"\"\"\" Utility methods for working with WSGI servers redux \"\"\"",
"args.pop('controller', None) fmt = args.pop('format', None) action = args.pop('action', None)",
"on an \"AS IS\" BASIS, WITHOUT # WARRANTIES OR CONDITIONS",
"2012 OpenStack Foundation. # All Rights Reserved. # # Licensed",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"('_error_context_msg', '_error_context_args'): if not hasattr(e, attr): return _('No details.') details",
"faults or {} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args = request.environ.get('wsgiorg.routing_args') if",
"details = e._error_context_msg args = e._error_context_args if args is _NO_ARGS_MARKER:",
"class Request(wsgi.Request): pass def Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API entity",
"import webob.dec from tacker.api import api_common from tacker import wsgi",
"< 500: LOG.info(_('%(action)s failed (client error): %(exc)s'), {'action': action, 'exc':",
"Rights Reserved. # # Licensed under the Apache License, Version",
"NOTE(jkoelker) Comply with RFC2616 section 9.7 if status == 204:",
"= faults or {} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args = request.environ.get('wsgiorg.routing_args')",
"request.body: args['body'] = deserializer.deserialize(request.body)['body'] method = getattr(controller, action) result =",
"= logging.getLogger(__name__) class Request(wsgi.Request): pass def Resource(controller, faults=None, deserializers=None, serializers=None):",
"OpenStack Foundation. # All Rights Reserved. # # Licensed under",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"faults=None, deserializers=None, serializers=None): \"\"\"API entity resource. Represents an API entity",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"{} # NOTE(jkoelker) by now the controller is already found,",
"= route_args[1].copy() else: args = {} # NOTE(jkoelker) by now",
"return _('No details.') details = e._error_context_msg args = e._error_context_args if",
"_NO_ARGS_MARKER = object() def extract_exc_details(e): for attr in ('_error_context_msg', '_error_context_args'):",
"Request(wsgi.Request): pass def Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API entity resource.",
"{'application/json': wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'} action_status = dict(create=201, delete=204)",
"resource _NO_ARGS_MARKER = object() def extract_exc_details(e): for attr in ('_error_context_msg',",
"= dict(create=201, delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers or {}) deserializers",
"content_type = '' body = None return webob.Response(request=request, status=status, content_type=content_type,",
"= object() def extract_exc_details(e): for attr in ('_error_context_msg', '_error_context_args'): if",
"compliance with the License. You may obtain # a copy",
"methods for working with WSGI servers redux \"\"\" from oslo_log",
"if args is _NO_ARGS_MARKER: return details return details % args",
"= {'json': 'application/json'} action_status = dict(create=201, delete=204) default_deserializers.update(deserializers or {})",
"matchdict args.pop('controller', None) fmt = args.pop('format', None) action = args.pop('action',",
"{ 'action': action, 'details': extract_exc_details(e), } ) raise mapped_exc status",
"= request.environ.get('wsgiorg.routing_args') if route_args: args = route_args[1].copy() else: args =",
"the # License for the specific language governing permissions and",
"status=status, content_type=content_type, body=body) return resource _NO_ARGS_MARKER = object() def extract_exc_details(e):",
"serializers=None): \"\"\"API entity resource. Represents an API entity resource and",
"# # Unless required by applicable law or agreed to",
"Comply with RFC2616 section 9.7 if status == 204: content_type",
"= api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc, 'code') and 400 <=",
"<= mapped_exc.code < 500: LOG.info(_('%(action)s failed (client error): %(exc)s'), {'action':",
"or {}) default_serializers.update(serializers or {}) deserializers = default_deserializers serializers =",
"serializer = serializers.get(content_type) try: if request.body: args['body'] = deserializer.deserialize(request.body)['body'] method",
"failed (client error): %(exc)s'), {'action': action, 'exc': mapped_exc}) else: LOG.exception(",
"hasattr(e, attr): return _('No details.') details = e._error_context_msg args =",
"method(request=request, **args) except Exception as e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults,",
"body = serializer.serialize(result) # NOTE(jkoelker) Comply with RFC2616 section 9.7",
"None return webob.Response(request=request, status=status, content_type=content_type, body=body) return resource _NO_ARGS_MARKER =",
"\"\"\" from oslo_log import log as logging import webob.dec from",
"2.0 (the \"License\"); you may # not use this file",
"NOTE(jkoelker) by now the controller is already found, remove #",
"WSGI servers redux \"\"\" from oslo_log import log as logging",
"400 <= mapped_exc.code < 500: LOG.info(_('%(action)s failed (client error): %(exc)s'),",
"args = e._error_context_args if args is _NO_ARGS_MARKER: return details return",
"by applicable law or agreed to in writing, software #",
"return resource _NO_ARGS_MARKER = object() def extract_exc_details(e): for attr in",
"default_serializers faults = faults or {} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args",
"deserializers.get(content_type) serializer = serializers.get(content_type) try: if request.body: args['body'] = deserializer.deserialize(request.body)['body']",
"serializers = default_serializers faults = faults or {} @webob.dec.wsgify(RequestClass=Request) def",
"BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either",
"route_args: args = route_args[1].copy() else: args = {} # NOTE(jkoelker)",
"'' body = None return webob.Response(request=request, status=status, content_type=content_type, body=body) return",
"wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'} action_status",
"format_types = {'json': 'application/json'} action_status = dict(create=201, delete=204) default_deserializers.update(deserializers or",
"serializer.serialize(result) # NOTE(jkoelker) Comply with RFC2616 section 9.7 if status",
"tacker.api import api_common from tacker import wsgi LOG = logging.getLogger(__name__)",
"try: if request.body: args['body'] = deserializer.deserialize(request.body)['body'] method = getattr(controller, action)",
"getattr(controller, action) result = method(request=request, **args) except Exception as e:",
"oslo_log import log as logging import webob.dec from tacker.api import",
"args = route_args[1].copy() else: args = {} # NOTE(jkoelker) by",
"it is in the matchdict args.pop('controller', None) fmt = args.pop('format',",
"\"\"\"API entity resource. Represents an API entity resource and the",
"= e._error_context_msg args = e._error_context_args if args is _NO_ARGS_MARKER: return",
"may obtain # a copy of the License at #",
"# Copyright 2012 OpenStack Foundation. # All Rights Reserved. #",
"# All Rights Reserved. # # Licensed under the Apache",
"LOG.info(_('%(action)s failed (client error): %(exc)s'), {'action': action, 'exc': mapped_exc}) else:",
"Unless required by applicable law or agreed to in writing,",
"wsgi.JSONDictSerializer()} format_types = {'json': 'application/json'} action_status = dict(create=201, delete=204) default_deserializers.update(deserializers",
"deserializer.deserialize(request.body)['body'] method = getattr(controller, action) result = method(request=request, **args) except",
"# NOTE(jkoelker) by now the controller is already found, remove",
"servers redux \"\"\" from oslo_log import log as logging import",
"applicable law or agreed to in writing, software # distributed",
"if request.body: args['body'] = deserializer.deserialize(request.body)['body'] method = getattr(controller, action) result",
"OF ANY KIND, either express or implied. See the #",
"default_serializers.update(serializers or {}) deserializers = default_deserializers serializers = default_serializers faults",
"WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"in writing, software # distributed under the License is distributed",
"'_error_context_args'): if not hasattr(e, attr): return _('No details.') details =",
"LOG.exception( _('%(action)s failed: %(details)s'), { 'action': action, 'details': extract_exc_details(e), }",
"= args.pop('format', None) action = args.pop('action', None) content_type = format_types.get(fmt,",
"= deserializer.deserialize(request.body)['body'] method = getattr(controller, action) result = method(request=request, **args)",
"it from the args if it is in the matchdict",
"pass def Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API entity resource. Represents",
"redux \"\"\" from oslo_log import log as logging import webob.dec",
"resource(request): route_args = request.environ.get('wsgiorg.routing_args') if route_args: args = route_args[1].copy() else:",
"# under the License. \"\"\" Utility methods for working with",
"'application/json'} action_status = dict(create=201, delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers or",
"either express or implied. See the # License for the",
"(client error): %(exc)s'), {'action': action, 'exc': mapped_exc}) else: LOG.exception( _('%(action)s",
"= request.best_match_language() deserializer = deserializers.get(content_type) serializer = serializers.get(content_type) try: if",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"may # not use this file except in compliance with",
"= '' body = None return webob.Response(request=request, status=status, content_type=content_type, body=body)",
"Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API entity resource. Represents an API",
"204: content_type = '' body = None return webob.Response(request=request, status=status,",
"as logging import webob.dec from tacker.api import api_common from tacker",
"# License for the specific language governing permissions and limitations",
"with the License. You may obtain # a copy of",
"you may # not use this file except in compliance",
"or {} @webob.dec.wsgify(RequestClass=Request) def resource(request): route_args = request.environ.get('wsgiorg.routing_args') if route_args:",
"in ('_error_context_msg', '_error_context_args'): if not hasattr(e, attr): return _('No details.')",
"api_common from tacker import wsgi LOG = logging.getLogger(__name__) class Request(wsgi.Request):",
"permissions and limitations # under the License. \"\"\" Utility methods",
"request.best_match_language() deserializer = deserializers.get(content_type) serializer = serializers.get(content_type) try: if request.body:",
"= serializer.serialize(result) # NOTE(jkoelker) Comply with RFC2616 section 9.7 if",
"e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc, 'code') and",
"LOG = logging.getLogger(__name__) class Request(wsgi.Request): pass def Resource(controller, faults=None, deserializers=None,",
"e._error_context_args if args is _NO_ARGS_MARKER: return details return details %",
"request.environ.get('wsgiorg.routing_args') if route_args: args = route_args[1].copy() else: args = {}",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"wsgi LOG = logging.getLogger(__name__) class Request(wsgi.Request): pass def Resource(controller, faults=None,",
"attr in ('_error_context_msg', '_error_context_args'): if not hasattr(e, attr): return _('No",
"action_status.get(action, 200) body = serializer.serialize(result) # NOTE(jkoelker) Comply with RFC2616",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"logging.getLogger(__name__) class Request(wsgi.Request): pass def Resource(controller, faults=None, deserializers=None, serializers=None): \"\"\"API",
"e._error_context_msg args = e._error_context_args if args is _NO_ARGS_MARKER: return details",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"%(details)s'), { 'action': action, 'details': extract_exc_details(e), } ) raise mapped_exc",
"faults, language) if hasattr(mapped_exc, 'code') and 400 <= mapped_exc.code <",
"section 9.7 if status == 204: content_type = '' body",
"default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json': wsgi.JSONDictSerializer()} format_types =",
"if route_args: args = route_args[1].copy() else: args = {} #",
"mapped_exc.code < 500: LOG.info(_('%(action)s failed (client error): %(exc)s'), {'action': action,",
"for the specific language governing permissions and limitations # under",
"_('No details.') details = e._error_context_msg args = e._error_context_args if args",
"Exception as e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc,",
"not hasattr(e, attr): return _('No details.') details = e._error_context_msg args",
"except in compliance with the License. You may obtain #",
"Foundation. # All Rights Reserved. # # Licensed under the",
"License. You may obtain # a copy of the License",
"deserialization logic \"\"\" default_deserializers = {'application/json': wsgi.JSONDeserializer()} default_serializers = {'application/json':",
"action, 'details': extract_exc_details(e), } ) raise mapped_exc status = action_status.get(action,",
"mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc, 'code') and 400",
"remove # it from the args if it is in",
"ANY KIND, either express or implied. See the # License",
"# distributed under the License is distributed on an \"AS",
"# Unless required by applicable law or agreed to in",
"} ) raise mapped_exc status = action_status.get(action, 200) body =",
"default_deserializers.update(deserializers or {}) default_serializers.update(serializers or {}) deserializers = default_deserializers serializers",
"is distributed on an \"AS IS\" BASIS, WITHOUT # WARRANTIES",
"under the License. \"\"\" Utility methods for working with WSGI",
"as e: mapped_exc = api_common.convert_exception_to_http_exc(e, faults, language) if hasattr(mapped_exc, 'code')",
"from oslo_log import log as logging import webob.dec from tacker.api",
"action_status = dict(create=201, delete=204) default_deserializers.update(deserializers or {}) default_serializers.update(serializers or {})",
"else: LOG.exception( _('%(action)s failed: %(details)s'), { 'action': action, 'details': extract_exc_details(e),",
"in the matchdict args.pop('controller', None) fmt = args.pop('format', None) action",
"details.') details = e._error_context_msg args = e._error_context_args if args is",
"or implied. See the # License for the specific language"
] |
[
"ans = str(ans).lower() if ans == \"yes\" or ans ==",
"The answer must be one of these: - \"yes\" OR",
"MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"\"i\" or ans == \"idk\" or ans == \"i dont",
"ans == \"pn\" or ans == \"4\": return \"4\" else:",
"{\"lang\": \"pl\", \"theme\": \"c\"} elif lang == \"pt\" or lang",
"or ans == \"4\": return \"4\" else: raise InvalidAnswerError(\"\"\" You",
"substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS",
"for Akinator\"\"\" ans = str(ans).lower() if ans == \"yes\" or",
"notice shall be included in all copies or substantial portions",
"\"en\", \"theme\": \"a\"} elif lang == \"en_objects\" or lang ==",
"\"italian\": return {\"lang\": \"it\", \"theme\": \"c\"} elif lang == \"it_animals\"",
"return {\"lang\": \"it\", \"theme\": \"a\"} elif lang == \"jp\" or",
"(c) 2019 NinjaSnail1080 Permission is hereby granted, free of charge,",
"or ans == \"y\" or ans == \"0\": return \"0\"",
"response == \"KO - TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers have",
"\"0\" elif ans == \"no\" or ans == \"n\" or",
"language\") elif response == \"KO - TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's",
"KNOW - \"probably\" OR \"p\" OR \"3\" for PROBABLY -",
"lang == \"spanish\": return {\"lang\": \"es\", \"theme\": \"c\"} elif lang",
"elif ans == \"probably\" or ans == \"p\" or ans",
"TIMEOUT\": raise AkiTimedOut(\"Your Akinator session has timed out\") elif response",
"lang == \"german\": return {\"lang\": \"de\", \"theme\": \"c\"} elif lang",
"return {\"lang\": \"pl\", \"theme\": \"c\"} elif lang == \"pt\" or",
"== \"ar\" or lang == \"arabic\": return {\"lang\": \"ar\", \"theme\":",
"ans == \"i don't know\" or ans == \"2\": return",
"theme based on what is input\"\"\" if lang is None",
"put \"{}\", which is an invalid answer. The answer must",
"this region. Try again later or use a different language\")",
"== \"english_objects\": return {\"lang\": \"en\", \"theme\": \"o\"} elif lang ==",
"{\"lang\": \"de\", \"theme\": \"a\"} elif lang == \"es\" or lang",
"== \"korean\": return {\"lang\": \"kr\", \"theme\": \"c\"} elif lang ==",
"error if the API failed to connect\"\"\" if response ==",
"a different language\") elif response == \"KO - TECHNICAL ERROR\":",
"elif response == \"KO - ELEM LIST IS EMPTY\" or",
"== \"KO - TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers have had",
"OR \"pn\" OR \"4\" for PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None):",
"\"es\", \"theme\": \"c\"} elif lang == \"es_animals\" or lang ==",
"the proper error if the API failed to connect\"\"\" if",
"ans == \"0\": return \"0\" elif ans == \"no\" or",
"code and theme based on what is input\"\"\" if lang",
"{\"lang\": \"it\", \"theme\": \"c\"} elif lang == \"it_animals\" or lang",
"Software without restriction, including without limitation the rights to use,",
"\"n\" or ans == \"1\": return \"1\" elif ans ==",
"80. No more questions\") else: raise AkiConnectionFailure(\"An unknown error has",
"and theme based on what is input\"\"\" if lang is",
"== \"dutch\": return {\"lang\": \"nl\", \"theme\": \"c\"} elif lang ==",
"Akinator\"\"\" ans = str(ans).lower() if ans == \"yes\" or ans",
"\"de_animals\" or lang == \"german_animals\": return {\"lang\": \"de\", \"theme\": \"a\"}",
"== \"fr\" or lang == \"french\": return {\"lang\": \"fr\", \"theme\":",
"\"spanish_animals\": return {\"lang\": \"es\", \"theme\": \"a\"} elif lang == \"fr\"",
"NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS",
"copies of the Software, and to permit persons to whom",
"NO - \"i\" OR \"idk\" OR \"i dont know\" OR",
"hereby granted, free of charge, to any person obtaining a",
"OR \"n\" OR \"1\" for NO - \"i\" OR \"idk\"",
"to deal in the Software without restriction, including without limitation",
"{\"lang\": \"ru\", \"theme\": \"c\"} elif lang == \"tr\" or lang",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"\"il\", \"theme\": \"c\"} elif lang == \"it\" or lang ==",
"\"english_animals\": return {\"lang\": \"en\", \"theme\": \"a\"} elif lang == \"en_objects\"",
"== \"WARN - NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No",
"if lang is None or lang == \"en\" or lang",
"elif lang == \"it\" or lang == \"italian\": return {\"lang\":",
"{\"lang\": \"fr\", \"theme\": \"c\"} elif lang == \"fr_animals\" or lang",
"\"a\"} elif lang == \"kr\" or lang == \"korean\": return",
"Answer ID for Akinator\"\"\" ans = str(ans).lower() if ans ==",
"portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\",",
"\"kr\" or lang == \"korean\": return {\"lang\": \"kr\", \"theme\": \"c\"}",
"or lang == \"english_objects\": return {\"lang\": \"en\", \"theme\": \"o\"} elif",
"\"c\"} elif lang == \"en_animals\" or lang == \"english_animals\": return",
"DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"lang == \"english_objects\": return {\"lang\": \"en\", \"theme\": \"o\"} elif lang",
"lang == \"fr\" or lang == \"french\": return {\"lang\": \"fr\",",
"\"a\"} elif lang == \"fr_objects\" or lang == \"french_objects\": return",
"return {\"lang\": \"fr\", \"theme\": \"c\"} elif lang == \"fr_animals\" or",
"modify, merge, publish, distribute, sublicense, and/or sell copies of the",
"don't know\" or ans == \"2\": return \"2\" elif ans",
"raise AkiServerDown(\"Akinator's servers are down in this region. Try again",
"ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"lang == \"jp\" or lang == \"japanese\": return {\"lang\": \"jp\",",
"persons to whom the Software is furnished to do so,",
"\"1\" elif ans == \"i\" or ans == \"idk\" or",
"limitation the rights to use, copy, modify, merge, publish, distribute,",
"subject to the following conditions: The above copyright notice and",
"OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH",
"ans == \"idk\" or ans == \"i dont know\" or",
"elif lang == \"ru\" or lang == \"russian\": return {\"lang\":",
"of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the proper error if the",
"lang == \"french_objects\": return {\"lang\": \"fr\", \"theme\": \"o\"} elif lang",
"know\" OR \"i don't know\" OR \"2\" for I DON'T",
"\"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the language code and theme based",
"\"it\", \"theme\": \"a\"} elif lang == \"jp\" or lang ==",
"\"jp_animals\" or lang == \"japanese_animals\": return {\"lang\": \"jp\", \"theme\": \"a\"}",
"\"theme\": \"c\"} elif lang == \"it_animals\" or lang == \"italian_animals\":",
"== \"pn\" or ans == \"4\": return \"4\" else: raise",
"must be one of these: - \"yes\" OR \"y\" OR",
"or ans == \"n\" or ans == \"1\": return \"1\"",
"an invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the proper error if",
"\"theme\": \"o\"} elif lang == \"ar\" or lang == \"arabic\":",
"\"chinese\": return {\"lang\": \"cn\", \"theme\": \"c\"} elif lang == \"de\"",
"API failed to connect\"\"\" if response == \"KO - SERVER",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A",
"ans == \"p\" or ans == \"3\": return \"3\" elif",
"lang == \"en\" or lang == \"english\": return {\"lang\": \"en\",",
"dont know\" OR \"i don't know\" OR \"2\" for I",
"return {\"lang\": \"es\", \"theme\": \"a\"} elif lang == \"fr\" or",
"Software is furnished to do so, subject to the following",
"\"turkish\": return {\"lang\": \"tr\", \"theme\": \"c\"} else: raise InvalidLanguageError(\"You put",
"Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"\"a\"} elif lang == \"fr\" or lang == \"french\": return",
"ans_to_id(ans): \"\"\"Convert an input answer string into an Answer ID",
"\"theme\": \"c\"} elif lang == \"it\" or lang == \"italian\":",
"\"pl\" or lang == \"polish\": return {\"lang\": \"pl\", \"theme\": \"c\"}",
"sell copies of the Software, and to permit persons to",
"- TIMEOUT\": raise AkiTimedOut(\"Your Akinator session has timed out\") elif",
"or lang == \"english\": return {\"lang\": \"en\", \"theme\": \"c\"} elif",
"included in all copies or substantial portions of the Software.",
"for PROBABLY - \"probably not\" OR \"pn\" OR \"4\" for",
"{\"lang\": \"nl\", \"theme\": \"c\"} elif lang == \"pl\" or lang",
"lang == \"en_animals\" or lang == \"english_animals\": return {\"lang\": \"en\",",
"OR \"1\" for NO - \"i\" OR \"idk\" OR \"i",
"return {\"lang\": \"tr\", \"theme\": \"c\"} else: raise InvalidLanguageError(\"You put \\\"{}\\\",",
"elif lang == \"kr\" or lang == \"korean\": return {\"lang\":",
"= str(ans).lower() if ans == \"yes\" or ans == \"y\"",
"copy, modify, merge, publish, distribute, sublicense, and/or sell copies of",
"lang == \"pt\" or lang == \"portuguese\": return {\"lang\": \"pt\",",
"\"1\": return \"1\" elif ans == \"i\" or ans ==",
"or lang == \"japanese_animals\": return {\"lang\": \"jp\", \"theme\": \"a\"} elif",
"lang == \"ru\" or lang == \"russian\": return {\"lang\": \"ru\",",
"\"WARN - NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more",
"elif lang == \"de\" or lang == \"german\": return {\"lang\":",
"\"probably\" OR \"p\" OR \"3\" for PROBABLY - \"probably not\"",
"\"theme\": \"c\"} elif lang == \"jp_animals\" or lang == \"japanese_animals\":",
"SERVER DOWN\": raise AkiServerDown(\"Akinator's servers are down in this region.",
"\"de\", \"theme\": \"c\"} elif lang == \"de_animals\" or lang ==",
"== \"cn\" or lang == \"chinese\": return {\"lang\": \"cn\", \"theme\":",
"\"french_animals\": return {\"lang\": \"fr\", \"theme\": \"a\"} elif lang == \"fr_objects\"",
"\"c\"} elif lang == \"pt\" or lang == \"portuguese\": return",
"furnished to do so, subject to the following conditions: The",
"or substantial portions of the Software. THE SOFTWARE IS PROVIDED",
"EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"ans == \"1\": return \"1\" elif ans == \"i\" or",
"these: - \"yes\" OR \"y\" OR \"0\" for YES -",
"Try again later or use a different language\") elif response",
"EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"know\" or ans == \"i don't know\" or ans ==",
"publish, distribute, sublicense, and/or sell copies of the Software, and",
"MIT License Copyright (c) 2019 NinjaSnail1080 Permission is hereby granted,",
"which is an invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the proper",
"\"Software\"), to deal in the Software without restriction, including without",
"== \"y\" or ans == \"0\": return \"0\" elif ans",
"for NO - \"i\" OR \"idk\" OR \"i dont know\"",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"lang == \"turkish\": return {\"lang\": \"tr\", \"theme\": \"c\"} else: raise",
"lang == \"italian\": return {\"lang\": \"it\", \"theme\": \"c\"} elif lang",
"AkiServerDown(\"Akinator's servers are down in this region. Try again later",
"or lang == \"english_animals\": return {\"lang\": \"en\", \"theme\": \"a\"} elif",
"import re import json def ans_to_id(ans): \"\"\"Convert an input answer",
"is None or lang == \"en\" or lang == \"english\":",
"later or use a different language\") elif response == \"KO",
"be included in all copies or substantial portions of the",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"or lang == \"german_animals\": return {\"lang\": \"de\", \"theme\": \"a\"} elif",
"OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from .exceptions import",
"lang == \"german_animals\": return {\"lang\": \"de\", \"theme\": \"a\"} elif lang",
"\"tr\", \"theme\": \"c\"} else: raise InvalidLanguageError(\"You put \\\"{}\\\", which is",
"\"c\"} elif lang == \"pl\" or lang == \"polish\": return",
"- TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers have had a technical",
"{\"lang\": \"pt\", \"theme\": \"c\"} elif lang == \"ru\" or lang",
"\"fr\", \"theme\": \"a\"} elif lang == \"fr_objects\" or lang ==",
"import json def ans_to_id(ans): \"\"\"Convert an input answer string into",
"know\" OR \"2\" for I DON'T KNOW - \"probably\" OR",
"lang == \"jp_animals\" or lang == \"japanese_animals\": return {\"lang\": \"jp\",",
"lang == \"japanese\": return {\"lang\": \"jp\", \"theme\": \"c\"} elif lang",
"\"c\"} elif lang == \"it_animals\" or lang == \"italian_animals\": return",
"\"theme\": \"a\"} elif lang == \"es\" or lang == \"spanish\":",
"AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import re import json def",
"elif lang == \"de_animals\" or lang == \"german_animals\": return {\"lang\":",
"raise AkiTechnicalError(\"Akinator's servers have had a technical error. Try again",
"== \"kr\" or lang == \"korean\": return {\"lang\": \"kr\", \"theme\":",
"the following conditions: The above copyright notice and this permission",
"response == \"KO - SERVER DOWN\": raise AkiServerDown(\"Akinator's servers are",
"files (the \"Software\"), to deal in the Software without restriction,",
"are down in this region. Try again later or use",
"\"en\", \"theme\": \"o\"} elif lang == \"ar\" or lang ==",
"\"fr\", \"theme\": \"o\"} elif lang == \"il\" or lang ==",
"== \"fr_animals\" or lang == \"french_animals\": return {\"lang\": \"fr\", \"theme\":",
"== \"KO - SERVER DOWN\": raise AkiServerDown(\"Akinator's servers are down",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF",
"invalid answer. The answer must be one of these: -",
"== \"italian\": return {\"lang\": \"it\", \"theme\": \"c\"} elif lang ==",
"the rights to use, copy, modify, merge, publish, distribute, sublicense,",
"or lang == \"hebrew\": return {\"lang\": \"il\", \"theme\": \"c\"} elif",
"\"theme\": \"a\"} elif lang == \"en_objects\" or lang == \"english_objects\":",
"software and associated documentation files (the \"Software\"), to deal in",
"== \"de_animals\" or lang == \"german_animals\": return {\"lang\": \"de\", \"theme\":",
"== \"japanese_animals\": return {\"lang\": \"jp\", \"theme\": \"a\"} elif lang ==",
"notice and this permission notice shall be included in all",
"or lang == \"polish\": return {\"lang\": \"pl\", \"theme\": \"c\"} elif",
"\"german_animals\": return {\"lang\": \"de\", \"theme\": \"a\"} elif lang == \"es\"",
"is hereby granted, free of charge, to any person obtaining",
"\"no\" OR \"n\" OR \"1\" for NO - \"i\" OR",
"\"3\" for PROBABLY - \"probably not\" OR \"pn\" OR \"4\"",
"a technical error. Try again later or use a different",
"or lang == \"chinese\": return {\"lang\": \"cn\", \"theme\": \"c\"} elif",
"or lang == \"french_objects\": return {\"lang\": \"fr\", \"theme\": \"o\"} elif",
"\"c\"} elif lang == \"de_animals\" or lang == \"german_animals\": return",
"== \"il\" or lang == \"hebrew\": return {\"lang\": \"il\", \"theme\":",
"== \"nl\" or lang == \"dutch\": return {\"lang\": \"nl\", \"theme\":",
"== \"i\" or ans == \"idk\" or ans == \"i",
"to the following conditions: The above copyright notice and this",
"conditions: The above copyright notice and this permission notice shall",
"\"n\" OR \"1\" for NO - \"i\" OR \"idk\" OR",
"the Software without restriction, including without limitation the rights to",
"for PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the language code",
"return {\"lang\": \"fr\", \"theme\": \"o\"} elif lang == \"il\" or",
"\"theme\": \"c\"} elif lang == \"fr_animals\" or lang == \"french_animals\":",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"elif lang == \"pl\" or lang == \"polish\": return {\"lang\":",
"\"2\" for I DON'T KNOW - \"probably\" OR \"p\" OR",
"proper error if the API failed to connect\"\"\" if response",
"the API failed to connect\"\"\" if response == \"KO -",
"THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND",
"language\") elif response == \"KO - TIMEOUT\": raise AkiTimedOut(\"Your Akinator",
"be one of these: - \"yes\" OR \"y\" OR \"0\"",
"== \"it\" or lang == \"italian\": return {\"lang\": \"it\", \"theme\":",
"and/or sell copies of the Software, and to permit persons",
"\"en_objects\" or lang == \"english_objects\": return {\"lang\": \"en\", \"theme\": \"o\"}",
"{\"lang\": \"en\", \"theme\": \"o\"} elif lang == \"ar\" or lang",
"permit persons to whom the Software is furnished to do",
"OR \"2\" for I DON'T KNOW - \"probably\" OR \"p\"",
"do so, subject to the following conditions: The above copyright",
"NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more questions\") else:",
"to connect\"\"\" if response == \"KO - SERVER DOWN\": raise",
"any person obtaining a copy of this software and associated",
"== \"en_objects\" or lang == \"english_objects\": return {\"lang\": \"en\", \"theme\":",
"return {\"lang\": \"fr\", \"theme\": \"a\"} elif lang == \"fr_objects\" or",
"or lang == \"japanese\": return {\"lang\": \"jp\", \"theme\": \"c\"} elif",
"LIST IS EMPTY\" or response == \"WARN - NO QUESTION\":",
"\"0\": return \"0\" elif ans == \"no\" or ans ==",
"lang == \"russian\": return {\"lang\": \"ru\", \"theme\": \"c\"} elif lang",
"language code and theme based on what is input\"\"\" if",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"\"i\" OR \"idk\" OR \"i dont know\" OR \"i don't",
"\"p\" or ans == \"3\": return \"3\" elif ans ==",
"AkiTimedOut(\"Your Akinator session has timed out\") elif response == \"KO",
"don't know\" OR \"2\" for I DON'T KNOW - \"probably\"",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"{\"lang\": \"jp\", \"theme\": \"a\"} elif lang == \"kr\" or lang",
"{\"lang\": \"en\", \"theme\": \"c\"} elif lang == \"en_animals\" or lang",
"THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"technical error. Try again later or use a different language\")",
"session has timed out\") elif response == \"KO - ELEM",
"\"dutch\": return {\"lang\": \"nl\", \"theme\": \"c\"} elif lang == \"pl\"",
"\"pt\" or lang == \"portuguese\": return {\"lang\": \"pt\", \"theme\": \"c\"}",
"{\"lang\": \"fr\", \"theme\": \"o\"} elif lang == \"il\" or lang",
"not\" OR \"pn\" OR \"4\" for PROBABLY NOT \"\"\".format(ans)) def",
"is input\"\"\" if lang is None or lang == \"en\"",
"copy of this software and associated documentation files (the \"Software\"),",
"\"nl\" or lang == \"dutch\": return {\"lang\": \"nl\", \"theme\": \"c\"}",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"\"pt\", \"theme\": \"c\"} elif lang == \"ru\" or lang ==",
"\"japanese\": return {\"lang\": \"jp\", \"theme\": \"c\"} elif lang == \"jp_animals\"",
"including without limitation the rights to use, copy, modify, merge,",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"\"polish\": return {\"lang\": \"pl\", \"theme\": \"c\"} elif lang == \"pt\"",
"lang == \"il\" or lang == \"hebrew\": return {\"lang\": \"il\",",
"or ans == \"i dont know\" or ans == \"i",
"or lang == \"portuguese\": return {\"lang\": \"pt\", \"theme\": \"c\"} elif",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"is an invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the proper error",
"re import json def ans_to_id(ans): \"\"\"Convert an input answer string",
".exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import",
"or lang == \"en\" or lang == \"english\": return {\"lang\":",
"\"a\"} elif lang == \"en_objects\" or lang == \"english_objects\": return",
"elif lang == \"fr\" or lang == \"french\": return {\"lang\":",
"if ans == \"yes\" or ans == \"y\" or ans",
"== \"english\": return {\"lang\": \"en\", \"theme\": \"c\"} elif lang ==",
"\"theme\": \"c\"} elif lang == \"en_animals\" or lang == \"english_animals\":",
"ERROR\": raise AkiTechnicalError(\"Akinator's servers have had a technical error. Try",
"InvalidLanguageError(\"You put \\\"{}\\\", which is an invalid language.\".format(lang)) def raise_connection_error(response):",
"without limitation the rights to use, copy, modify, merge, publish,",
"\"c\"} elif lang == \"nl\" or lang == \"dutch\": return",
"\"idk\" or ans == \"i dont know\" or ans ==",
"\"\"\" MIT License Copyright (c) 2019 NinjaSnail1080 Permission is hereby",
"- NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more questions\")",
"lang == \"de\" or lang == \"german\": return {\"lang\": \"de\",",
"ID for Akinator\"\"\" ans = str(ans).lower() if ans == \"yes\"",
"restriction, including without limitation the rights to use, copy, modify,",
"\"nl\", \"theme\": \"c\"} elif lang == \"pl\" or lang ==",
"different language\") elif response == \"KO - TECHNICAL ERROR\": raise",
"response == \"WARN - NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80.",
"to permit persons to whom the Software is furnished to",
"elif lang == \"it_animals\" or lang == \"italian_animals\": return {\"lang\":",
"== \"french_objects\": return {\"lang\": \"fr\", \"theme\": \"o\"} elif lang ==",
"on what is input\"\"\" if lang is None or lang",
"\"jp\" or lang == \"japanese\": return {\"lang\": \"jp\", \"theme\": \"c\"}",
"== \"0\": return \"0\" elif ans == \"no\" or ans",
"YES - \"no\" OR \"n\" OR \"1\" for NO -",
"lang == \"es_animals\" or lang == \"spanish_animals\": return {\"lang\": \"es\",",
"\"c\"} elif lang == \"it\" or lang == \"italian\": return",
"{\"lang\": \"fr\", \"theme\": \"a\"} elif lang == \"fr_objects\" or lang",
"based on what is input\"\"\" if lang is None or",
"OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"ans == \"4\": return \"4\" else: raise InvalidAnswerError(\"\"\" You put",
"lang == \"ar\" or lang == \"arabic\": return {\"lang\": \"ar\",",
"return {\"lang\": \"en\", \"theme\": \"a\"} elif lang == \"en_objects\" or",
"again later or use a different language\") elif response ==",
"\"pn\" OR \"4\" for PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns",
"InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import re import",
"== \"spanish_animals\": return {\"lang\": \"es\", \"theme\": \"a\"} elif lang ==",
"== \"italian_animals\": return {\"lang\": \"it\", \"theme\": \"a\"} elif lang ==",
"or use a different language\") elif response == \"KO -",
"OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"License Copyright (c) 2019 NinjaSnail1080 Permission is hereby granted, free",
"deal in the Software without restriction, including without limitation the",
"return {\"lang\": \"ru\", \"theme\": \"c\"} elif lang == \"tr\" or",
"elif lang == \"pt\" or lang == \"portuguese\": return {\"lang\":",
"\"jp\", \"theme\": \"a\"} elif lang == \"kr\" or lang ==",
"\"4\" else: raise InvalidAnswerError(\"\"\" You put \"{}\", which is an",
"elif lang == \"fr_objects\" or lang == \"french_objects\": return {\"lang\":",
"== \"portuguese\": return {\"lang\": \"pt\", \"theme\": \"c\"} elif lang ==",
"return {\"lang\": \"jp\", \"theme\": \"c\"} elif lang == \"jp_animals\" or",
"\"jp\", \"theme\": \"c\"} elif lang == \"jp_animals\" or lang ==",
"elif lang == \"jp_animals\" or lang == \"japanese_animals\": return {\"lang\":",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR",
"input\"\"\" if lang is None or lang == \"en\" or",
"== \"arabic\": return {\"lang\": \"ar\", \"theme\": \"c\"} elif lang ==",
"\"russian\": return {\"lang\": \"ru\", \"theme\": \"c\"} elif lang == \"tr\"",
"ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO",
"\"c\"} elif lang == \"de\" or lang == \"german\": return",
"AkiServerDown, AkiTechnicalError import re import json def ans_to_id(ans): \"\"\"Convert an",
"distribute, sublicense, and/or sell copies of the Software, and to",
"\"theme\": \"c\"} elif lang == \"cn\" or lang == \"chinese\":",
"return {\"lang\": \"jp\", \"theme\": \"a\"} elif lang == \"kr\" or",
"has timed out\") elif response == \"KO - ELEM LIST",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR",
"ans == \"i dont know\" or ans == \"i don't",
"\"i don't know\" or ans == \"2\": return \"2\" elif",
"\"3\" elif ans == \"probably not\" or ans == \"pn\"",
"return {\"lang\": \"kr\", \"theme\": \"c\"} elif lang == \"nl\" or",
"lang == \"french\": return {\"lang\": \"fr\", \"theme\": \"c\"} elif lang",
"else: raise InvalidLanguageError(\"You put \\\"{}\\\", which is an invalid language.\".format(lang))",
"\"y\" OR \"0\" for YES - \"no\" OR \"n\" OR",
"\"arabic\": return {\"lang\": \"ar\", \"theme\": \"c\"} elif lang == \"cn\"",
"{\"lang\": \"kr\", \"theme\": \"c\"} elif lang == \"nl\" or lang",
"== \"it_animals\" or lang == \"italian_animals\": return {\"lang\": \"it\", \"theme\":",
"the Software, and to permit persons to whom the Software",
"return {\"lang\": \"en\", \"theme\": \"o\"} elif lang == \"ar\" or",
"region. Try again later or use a different language\") elif",
"and associated documentation files (the \"Software\"), to deal in the",
"- \"probably not\" OR \"pn\" OR \"4\" for PROBABLY NOT",
"== \"english_animals\": return {\"lang\": \"en\", \"theme\": \"a\"} elif lang ==",
"\"o\"} elif lang == \"ar\" or lang == \"arabic\": return",
"\"i dont know\" OR \"i don't know\" OR \"2\" for",
"{\"lang\": \"jp\", \"theme\": \"c\"} elif lang == \"jp_animals\" or lang",
"lang == \"korean\": return {\"lang\": \"kr\", \"theme\": \"c\"} elif lang",
"lang == \"spanish_animals\": return {\"lang\": \"es\", \"theme\": \"a\"} elif lang",
"\"c\"} elif lang == \"tr\" or lang == \"turkish\": return",
"\"tr\" or lang == \"turkish\": return {\"lang\": \"tr\", \"theme\": \"c\"}",
"return {\"lang\": \"pt\", \"theme\": \"c\"} elif lang == \"ru\" or",
"the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"\"cn\" or lang == \"chinese\": return {\"lang\": \"cn\", \"theme\": \"c\"}",
"to whom the Software is furnished to do so, subject",
"\"\"\"Raise the proper error if the API failed to connect\"\"\"",
"TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers have had a technical error.",
"- ELEM LIST IS EMPTY\" or response == \"WARN -",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"\"p\" OR \"3\" for PROBABLY - \"probably not\" OR \"pn\"",
"== \"idk\" or ans == \"i dont know\" or ans",
"\"3\": return \"3\" elif ans == \"probably not\" or ans",
"== \"3\": return \"3\" elif ans == \"probably not\" or",
"\"fr_animals\" or lang == \"french_animals\": return {\"lang\": \"fr\", \"theme\": \"a\"}",
"lang == \"nl\" or lang == \"dutch\": return {\"lang\": \"nl\",",
"PROBABLY - \"probably not\" OR \"pn\" OR \"4\" for PROBABLY",
"DON'T KNOW - \"probably\" OR \"p\" OR \"3\" for PROBABLY",
"WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT",
"\"theme\": \"c\"} elif lang == \"de_animals\" or lang == \"german_animals\":",
"lang == \"it\" or lang == \"italian\": return {\"lang\": \"it\",",
"OR \"3\" for PROBABLY - \"probably not\" OR \"pn\" OR",
"== \"german_animals\": return {\"lang\": \"de\", \"theme\": \"a\"} elif lang ==",
"the language code and theme based on what is input\"\"\"",
"{\"lang\": \"en\", \"theme\": \"a\"} elif lang == \"en_objects\" or lang",
"TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE",
"== \"de\" or lang == \"german\": return {\"lang\": \"de\", \"theme\":",
"lang == \"fr_objects\" or lang == \"french_objects\": return {\"lang\": \"fr\",",
"answer must be one of these: - \"yes\" OR \"y\"",
"OR \"p\" OR \"3\" for PROBABLY - \"probably not\" OR",
"\"italian_animals\": return {\"lang\": \"it\", \"theme\": \"a\"} elif lang == \"jp\"",
"elif lang == \"ar\" or lang == \"arabic\": return {\"lang\":",
"lang == \"chinese\": return {\"lang\": \"cn\", \"theme\": \"c\"} elif lang",
"raise InvalidLanguageError(\"You put \\\"{}\\\", which is an invalid language.\".format(lang)) def",
"\"theme\": \"c\"} elif lang == \"pl\" or lang == \"polish\":",
"{\"lang\": \"ar\", \"theme\": \"c\"} elif lang == \"cn\" or lang",
"of the Software, and to permit persons to whom the",
"this software and associated documentation files (the \"Software\"), to deal",
"answer string into an Answer ID for Akinator\"\"\" ans =",
"lang == \"polish\": return {\"lang\": \"pl\", \"theme\": \"c\"} elif lang",
"== \"n\" or ans == \"1\": return \"1\" elif ans",
"all copies or substantial portions of the Software. THE SOFTWARE",
"failed to connect\"\"\" if response == \"KO - SERVER DOWN\":",
"\"2\": return \"2\" elif ans == \"probably\" or ans ==",
"\"theme\": \"c\"} elif lang == \"tr\" or lang == \"turkish\":",
"(the \"Software\"), to deal in the Software without restriction, including",
"AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more questions\") else: raise AkiConnectionFailure(\"An unknown",
"ans == \"i\" or ans == \"idk\" or ans ==",
"OR \"y\" OR \"0\" for YES - \"no\" OR \"n\"",
"merge, publish, distribute, sublicense, and/or sell copies of the Software,",
"== \"fr_objects\" or lang == \"french_objects\": return {\"lang\": \"fr\", \"theme\":",
"QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more questions\") else: raise",
"== \"i don't know\" or ans == \"2\": return \"2\"",
"return \"3\" elif ans == \"probably not\" or ans ==",
"so, subject to the following conditions: The above copyright notice",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"ans == \"no\" or ans == \"n\" or ans ==",
"charge, to any person obtaining a copy of this software",
"to do so, subject to the following conditions: The above",
"WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"AkiNoQuestions, AkiServerDown, AkiTechnicalError import re import json def ans_to_id(ans): \"\"\"Convert",
"== \"pt\" or lang == \"portuguese\": return {\"lang\": \"pt\", \"theme\":",
"\"KO - ELEM LIST IS EMPTY\" or response == \"WARN",
"following conditions: The above copyright notice and this permission notice",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"NinjaSnail1080 Permission is hereby granted, free of charge, to any",
"ans == \"probably\" or ans == \"p\" or ans ==",
"\"english_objects\": return {\"lang\": \"en\", \"theme\": \"o\"} elif lang == \"ar\"",
"lang == \"english\": return {\"lang\": \"en\", \"theme\": \"c\"} elif lang",
"== \"russian\": return {\"lang\": \"ru\", \"theme\": \"c\"} elif lang ==",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"\"french_objects\": return {\"lang\": \"fr\", \"theme\": \"o\"} elif lang == \"il\"",
"elif ans == \"i\" or ans == \"idk\" or ans",
"OTHER DEALINGS IN THE SOFTWARE. \"\"\" from .exceptions import InvalidAnswerError,",
"elif ans == \"probably not\" or ans == \"pn\" or",
"response == \"KO - ELEM LIST IS EMPTY\" or response",
"input answer string into an Answer ID for Akinator\"\"\" ans",
"in the Software without restriction, including without limitation the rights",
"permission notice shall be included in all copies or substantial",
"\"{}\", which is an invalid answer. The answer must be",
"elif lang == \"fr_animals\" or lang == \"french_animals\": return {\"lang\":",
"return {\"lang\": \"de\", \"theme\": \"c\"} elif lang == \"de_animals\" or",
"lang == \"tr\" or lang == \"turkish\": return {\"lang\": \"tr\",",
"DOWN\": raise AkiServerDown(\"Akinator's servers are down in this region. Try",
"\"theme\": \"c\"} elif lang == \"es_animals\" or lang == \"spanish_animals\":",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"lang == \"en_objects\" or lang == \"english_objects\": return {\"lang\": \"en\",",
"\"kr\", \"theme\": \"c\"} elif lang == \"nl\" or lang ==",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER",
"2019 NinjaSnail1080 Permission is hereby granted, free of charge, to",
"or ans == \"2\": return \"2\" elif ans == \"probably\"",
"\"cn\", \"theme\": \"c\"} elif lang == \"de\" or lang ==",
"into an Answer ID for Akinator\"\"\" ans = str(ans).lower() if",
"more questions\") else: raise AkiConnectionFailure(\"An unknown error has occured. Server",
"\"theme\": \"a\"} elif lang == \"jp\" or lang == \"japanese\":",
"timed out\") elif response == \"KO - ELEM LIST IS",
"\"4\" for PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the language",
"lang == \"kr\" or lang == \"korean\": return {\"lang\": \"kr\",",
"None or lang == \"en\" or lang == \"english\": return",
"or lang == \"russian\": return {\"lang\": \"ru\", \"theme\": \"c\"} elif",
"- \"probably\" OR \"p\" OR \"3\" for PROBABLY - \"probably",
"== \"probably not\" or ans == \"pn\" or ans ==",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS",
"response == \"KO - TIMEOUT\": raise AkiTimedOut(\"Your Akinator session has",
"return \"0\" elif ans == \"no\" or ans == \"n\"",
"ELEM LIST IS EMPTY\" or response == \"WARN - NO",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,",
"\"ru\", \"theme\": \"c\"} elif lang == \"tr\" or lang ==",
"\"pn\" or ans == \"4\": return \"4\" else: raise InvalidAnswerError(\"\"\"",
"return \"4\" else: raise InvalidAnswerError(\"\"\" You put \"{}\", which is",
"{\"lang\": \"il\", \"theme\": \"c\"} elif lang == \"it\" or lang",
"copyright notice and this permission notice shall be included in",
"\"i don't know\" OR \"2\" for I DON'T KNOW -",
"else: raise AkiConnectionFailure(\"An unknown error has occured. Server response: {}\".format(response))",
"string into an Answer ID for Akinator\"\"\" ans = str(ans).lower()",
"\"KO - TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers have had a",
"or ans == \"0\": return \"0\" elif ans == \"no\"",
"OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\"",
"\"theme\": \"o\"} elif lang == \"il\" or lang == \"hebrew\":",
"\"\"\"Convert an input answer string into an Answer ID for",
"IS EMPTY\" or response == \"WARN - NO QUESTION\": raise",
"== \"1\": return \"1\" elif ans == \"i\" or ans",
"PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the language code and",
"and to permit persons to whom the Software is furnished",
"\"it\" or lang == \"italian\": return {\"lang\": \"it\", \"theme\": \"c\"}",
"- \"yes\" OR \"y\" OR \"0\" for YES - \"no\"",
"error. Try again later or use a different language\") elif",
"copies or substantial portions of the Software. THE SOFTWARE IS",
"\"fr\", \"theme\": \"c\"} elif lang == \"fr_animals\" or lang ==",
"OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED",
"elif lang == \"es_animals\" or lang == \"spanish_animals\": return {\"lang\":",
"\"c\"} elif lang == \"fr_animals\" or lang == \"french_animals\": return",
"\"4\": return \"4\" else: raise InvalidAnswerError(\"\"\" You put \"{}\", which",
"put \\\"{}\\\", which is an invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise",
"or lang == \"italian_animals\": return {\"lang\": \"it\", \"theme\": \"a\"} elif",
"\"theme\": \"c\"} elif lang == \"nl\" or lang == \"dutch\":",
"if response == \"KO - SERVER DOWN\": raise AkiServerDown(\"Akinator's servers",
"use a different language\") elif response == \"KO - TECHNICAL",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"\"y\" or ans == \"0\": return \"0\" elif ans ==",
"== \"hebrew\": return {\"lang\": \"il\", \"theme\": \"c\"} elif lang ==",
"OR \"i dont know\" OR \"i don't know\" OR \"2\"",
"lang == \"de_animals\" or lang == \"german_animals\": return {\"lang\": \"de\",",
"lang == \"hebrew\": return {\"lang\": \"il\", \"theme\": \"c\"} elif lang",
"== \"jp\" or lang == \"japanese\": return {\"lang\": \"jp\", \"theme\":",
"USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from .exceptions",
"or lang == \"dutch\": return {\"lang\": \"nl\", \"theme\": \"c\"} elif",
"== \"chinese\": return {\"lang\": \"cn\", \"theme\": \"c\"} elif lang ==",
"or ans == \"p\" or ans == \"3\": return \"3\"",
"\"theme\": \"c\"} else: raise InvalidLanguageError(\"You put \\\"{}\\\", which is an",
"whom the Software is furnished to do so, subject to",
"know\" or ans == \"2\": return \"2\" elif ans ==",
"\"english\": return {\"lang\": \"en\", \"theme\": \"c\"} elif lang == \"en_animals\"",
"InvalidAnswerError(\"\"\" You put \"{}\", which is an invalid answer. The",
"<reponame>GitHubEmploy/akinator.py \"\"\" MIT License Copyright (c) 2019 NinjaSnail1080 Permission is",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT",
"elif lang == \"jp\" or lang == \"japanese\": return {\"lang\":",
"or ans == \"idk\" or ans == \"i dont know\"",
"\"a\"} elif lang == \"es\" or lang == \"spanish\": return",
"- \"no\" OR \"n\" OR \"1\" for NO - \"i\"",
"in all copies or substantial portions of the Software. THE",
"an invalid answer. The answer must be one of these:",
"obtaining a copy of this software and associated documentation files",
"\"theme\": \"c\"} elif lang == \"pt\" or lang == \"portuguese\":",
"an input answer string into an Answer ID for Akinator\"\"\"",
"OR \"0\" for YES - \"no\" OR \"n\" OR \"1\"",
"\"german\": return {\"lang\": \"de\", \"theme\": \"c\"} elif lang == \"de_animals\"",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN",
"== \"en\" or lang == \"english\": return {\"lang\": \"en\", \"theme\":",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"a copy of this software and associated documentation files (the",
"or ans == \"pn\" or ans == \"4\": return \"4\"",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"return \"1\" elif ans == \"i\" or ans == \"idk\"",
"lang == \"pl\" or lang == \"polish\": return {\"lang\": \"pl\",",
"ans == \"2\": return \"2\" elif ans == \"probably\" or",
"OR \"idk\" OR \"i dont know\" OR \"i don't know\"",
"return {\"lang\": \"it\", \"theme\": \"c\"} elif lang == \"it_animals\" or",
"sublicense, and/or sell copies of the Software, and to permit",
"== \"french_animals\": return {\"lang\": \"fr\", \"theme\": \"a\"} elif lang ==",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR",
"\"c\"} elif lang == \"ru\" or lang == \"russian\": return",
"== \"pl\" or lang == \"polish\": return {\"lang\": \"pl\", \"theme\":",
"You put \"{}\", which is an invalid answer. The answer",
"what is input\"\"\" if lang is None or lang ==",
"{\"lang\": \"es\", \"theme\": \"c\"} elif lang == \"es_animals\" or lang",
"from .exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError",
"\"no\" or ans == \"n\" or ans == \"1\": return",
"\"de\" or lang == \"german\": return {\"lang\": \"de\", \"theme\": \"c\"}",
"\"de\", \"theme\": \"a\"} elif lang == \"es\" or lang ==",
"OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"for I DON'T KNOW - \"probably\" OR \"p\" OR \"3\"",
"answer. The answer must be one of these: - \"yes\"",
"in this region. Try again later or use a different",
"== \"japanese\": return {\"lang\": \"jp\", \"theme\": \"c\"} elif lang ==",
"{\"lang\": \"it\", \"theme\": \"a\"} elif lang == \"jp\" or lang",
"lang == \"dutch\": return {\"lang\": \"nl\", \"theme\": \"c\"} elif lang",
"\"yes\" OR \"y\" OR \"0\" for YES - \"no\" OR",
"CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF",
"elif lang == \"nl\" or lang == \"dutch\": return {\"lang\":",
"lang is None or lang == \"en\" or lang ==",
"this permission notice shall be included in all copies or",
"== \"es_animals\" or lang == \"spanish_animals\": return {\"lang\": \"es\", \"theme\":",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN",
"\"c\"} else: raise InvalidLanguageError(\"You put \\\"{}\\\", which is an invalid",
"== \"KO - ELEM LIST IS EMPTY\" or response ==",
"\"idk\" OR \"i dont know\" OR \"i don't know\" OR",
"above copyright notice and this permission notice shall be included",
"of these: - \"yes\" OR \"y\" OR \"0\" for YES",
"== \"spanish\": return {\"lang\": \"es\", \"theme\": \"c\"} elif lang ==",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"or ans == \"1\": return \"1\" elif ans == \"i\"",
"\"korean\": return {\"lang\": \"kr\", \"theme\": \"c\"} elif lang == \"nl\"",
"lang == \"arabic\": return {\"lang\": \"ar\", \"theme\": \"c\"} elif lang",
"json def ans_to_id(ans): \"\"\"Convert an input answer string into an",
"ans == \"3\": return \"3\" elif ans == \"probably not\"",
"\"portuguese\": return {\"lang\": \"pt\", \"theme\": \"c\"} elif lang == \"ru\"",
"{\"lang\": \"es\", \"theme\": \"a\"} elif lang == \"fr\" or lang",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,",
"== \"probably\" or ans == \"p\" or ans == \"3\":",
"\"c\"} elif lang == \"jp_animals\" or lang == \"japanese_animals\": return",
"Akinator session has timed out\") elif response == \"KO -",
"an Answer ID for Akinator\"\"\" ans = str(ans).lower() if ans",
"lang == \"es\" or lang == \"spanish\": return {\"lang\": \"es\",",
"elif lang == \"en_objects\" or lang == \"english_objects\": return {\"lang\":",
"out\") elif response == \"KO - ELEM LIST IS EMPTY\"",
"InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import re import json",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING",
"KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"is furnished to do so, subject to the following conditions:",
"is an invalid answer. The answer must be one of",
"have had a technical error. Try again later or use",
"one of these: - \"yes\" OR \"y\" OR \"0\" for",
"== \"yes\" or ans == \"y\" or ans == \"0\":",
"elif lang == \"en_animals\" or lang == \"english_animals\": return {\"lang\":",
"str(ans).lower() if ans == \"yes\" or ans == \"y\" or",
"No more questions\") else: raise AkiConnectionFailure(\"An unknown error has occured.",
"lang == \"english_animals\": return {\"lang\": \"en\", \"theme\": \"a\"} elif lang",
"{\"lang\": \"de\", \"theme\": \"c\"} elif lang == \"de_animals\" or lang",
"or lang == \"french\": return {\"lang\": \"fr\", \"theme\": \"c\"} elif",
"or response == \"WARN - NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached",
"- \"i\" OR \"idk\" OR \"i dont know\" OR \"i",
"\"c\"} elif lang == \"cn\" or lang == \"chinese\": return",
"to any person obtaining a copy of this software and",
"\"KO - TIMEOUT\": raise AkiTimedOut(\"Your Akinator session has timed out\")",
"{\"lang\": \"tr\", \"theme\": \"c\"} else: raise InvalidLanguageError(\"You put \\\"{}\\\", which",
"OR \"4\" for PROBABLY NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the",
"\"o\"} elif lang == \"il\" or lang == \"hebrew\": return",
"\"en_animals\" or lang == \"english_animals\": return {\"lang\": \"en\", \"theme\": \"a\"}",
"== \"es\" or lang == \"spanish\": return {\"lang\": \"es\", \"theme\":",
"\"es\", \"theme\": \"a\"} elif lang == \"fr\" or lang ==",
"import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import re",
"shall be included in all copies or substantial portions of",
"person obtaining a copy of this software and associated documentation",
"or lang == \"french_animals\": return {\"lang\": \"fr\", \"theme\": \"a\"} elif",
"FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN",
"for YES - \"no\" OR \"n\" OR \"1\" for NO",
"OR \"i don't know\" OR \"2\" for I DON'T KNOW",
"or lang == \"turkish\": return {\"lang\": \"tr\", \"theme\": \"c\"} else:",
"return {\"lang\": \"il\", \"theme\": \"c\"} elif lang == \"it\" or",
"\"theme\": \"a\"} elif lang == \"kr\" or lang == \"korean\":",
"and this permission notice shall be included in all copies",
"elif ans == \"no\" or ans == \"n\" or ans",
"AkiTimedOut, AkiNoQuestions, AkiServerDown, AkiTechnicalError import re import json def ans_to_id(ans):",
"\"es\" or lang == \"spanish\": return {\"lang\": \"es\", \"theme\": \"c\"}",
"lang == \"it_animals\" or lang == \"italian_animals\": return {\"lang\": \"it\",",
"not\" or ans == \"pn\" or ans == \"4\": return",
"use a different language\") elif response == \"KO - TIMEOUT\":",
"SOFTWARE. \"\"\" from .exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions,",
"def get_lang_and_theme(lang=None): \"\"\"Returns the language code and theme based on",
"return \"2\" elif ans == \"probably\" or ans == \"p\"",
"questions\") else: raise AkiConnectionFailure(\"An unknown error has occured. Server response:",
"servers are down in this region. Try again later or",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT",
"ans == \"n\" or ans == \"1\": return \"1\" elif",
"== \"no\" or ans == \"n\" or ans == \"1\":",
"ans == \"probably not\" or ans == \"pn\" or ans",
"\"ar\", \"theme\": \"c\"} elif lang == \"cn\" or lang ==",
"{\"lang\": \"cn\", \"theme\": \"c\"} elif lang == \"de\" or lang",
"return {\"lang\": \"ar\", \"theme\": \"c\"} elif lang == \"cn\" or",
"I DON'T KNOW - \"probably\" OR \"p\" OR \"3\" for",
"lang == \"cn\" or lang == \"chinese\": return {\"lang\": \"cn\",",
"def ans_to_id(ans): \"\"\"Convert an input answer string into an Answer",
"raise AkiNoQuestions(\"\\\"Akinator.step\\\" reached 80. No more questions\") else: raise AkiConnectionFailure(\"An",
"OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE",
"AkiTechnicalError import re import json def ans_to_id(ans): \"\"\"Convert an input",
"free of charge, to any person obtaining a copy of",
"== \"en_animals\" or lang == \"english_animals\": return {\"lang\": \"en\", \"theme\":",
"== \"ru\" or lang == \"russian\": return {\"lang\": \"ru\", \"theme\":",
"IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE",
"\"french\": return {\"lang\": \"fr\", \"theme\": \"c\"} elif lang == \"fr_animals\"",
"elif lang == \"es\" or lang == \"spanish\": return {\"lang\":",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"\"0\" for YES - \"no\" OR \"n\" OR \"1\" for",
"or lang == \"spanish_animals\": return {\"lang\": \"es\", \"theme\": \"a\"} elif",
"different language\") elif response == \"KO - TIMEOUT\": raise AkiTimedOut(\"Your",
"OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"the Software is furnished to do so, subject to the",
"Software, and to permit persons to whom the Software is",
"which is an invalid answer. The answer must be one",
"lang == \"italian_animals\": return {\"lang\": \"it\", \"theme\": \"a\"} elif lang",
"\"theme\": \"a\"} elif lang == \"fr_objects\" or lang == \"french_objects\":",
"connect\"\"\" if response == \"KO - SERVER DOWN\": raise AkiServerDown(\"Akinator's",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.",
"servers have had a technical error. Try again later or",
"raise AkiTimedOut(\"Your Akinator session has timed out\") elif response ==",
"== \"4\": return \"4\" else: raise InvalidAnswerError(\"\"\" You put \"{}\",",
"== \"tr\" or lang == \"turkish\": return {\"lang\": \"tr\", \"theme\":",
"\"i dont know\" or ans == \"i don't know\" or",
"\"theme\": \"c\"} elif lang == \"de\" or lang == \"german\":",
"rights to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"\"theme\": \"a\"} elif lang == \"fr\" or lang == \"french\":",
"def raise_connection_error(response): \"\"\"Raise the proper error if the API failed",
"\"en\" or lang == \"english\": return {\"lang\": \"en\", \"theme\": \"c\"}",
"NOT \"\"\".format(ans)) def get_lang_and_theme(lang=None): \"\"\"Returns the language code and theme",
"documentation files (the \"Software\"), to deal in the Software without",
"\"probably\" or ans == \"p\" or ans == \"3\": return",
"\"a\"} elif lang == \"jp\" or lang == \"japanese\": return",
"lang == \"portuguese\": return {\"lang\": \"pt\", \"theme\": \"c\"} elif lang",
"== \"jp_animals\" or lang == \"japanese_animals\": return {\"lang\": \"jp\", \"theme\":",
"IN THE SOFTWARE. \"\"\" from .exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure,",
"without restriction, including without limitation the rights to use, copy,",
"down in this region. Try again later or use a",
"or lang == \"italian\": return {\"lang\": \"it\", \"theme\": \"c\"} elif",
"return {\"lang\": \"cn\", \"theme\": \"c\"} elif lang == \"de\" or",
"\"pl\", \"theme\": \"c\"} elif lang == \"pt\" or lang ==",
"or ans == \"3\": return \"3\" elif ans == \"probably",
"TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION",
"== \"i dont know\" or ans == \"i don't know\"",
"EMPTY\" or response == \"WARN - NO QUESTION\": raise AkiNoQuestions(\"\\\"Akinator.step\\\"",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"\"il\" or lang == \"hebrew\": return {\"lang\": \"il\", \"theme\": \"c\"}",
"ans == \"y\" or ans == \"0\": return \"0\" elif",
"lang == \"japanese_animals\": return {\"lang\": \"jp\", \"theme\": \"a\"} elif lang",
"\"probably not\" or ans == \"pn\" or ans == \"4\":",
"\"yes\" or ans == \"y\" or ans == \"0\": return",
"get_lang_and_theme(lang=None): \"\"\"Returns the language code and theme based on what",
"- SERVER DOWN\": raise AkiServerDown(\"Akinator's servers are down in this",
"\"hebrew\": return {\"lang\": \"il\", \"theme\": \"c\"} elif lang == \"it\"",
"elif response == \"KO - TIMEOUT\": raise AkiTimedOut(\"Your Akinator session",
"== \"KO - TIMEOUT\": raise AkiTimedOut(\"Your Akinator session has timed",
"NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"\"ar\" or lang == \"arabic\": return {\"lang\": \"ar\", \"theme\": \"c\"}",
"\"c\"} elif lang == \"es_animals\" or lang == \"spanish_animals\": return",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies",
"== \"2\": return \"2\" elif ans == \"probably\" or ans",
"\"ru\" or lang == \"russian\": return {\"lang\": \"ru\", \"theme\": \"c\"}",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR",
"lang == \"fr_animals\" or lang == \"french_animals\": return {\"lang\": \"fr\",",
"\\\"{}\\\", which is an invalid language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the",
"granted, free of charge, to any person obtaining a copy",
"\"1\" for NO - \"i\" OR \"idk\" OR \"i dont",
"\"2\" elif ans == \"probably\" or ans == \"p\" or",
"elif lang == \"tr\" or lang == \"turkish\": return {\"lang\":",
"DEALINGS IN THE SOFTWARE. \"\"\" from .exceptions import InvalidAnswerError, InvalidLanguageError,",
"raise_connection_error(response): \"\"\"Raise the proper error if the API failed to",
"Copyright (c) 2019 NinjaSnail1080 Permission is hereby granted, free of",
"return {\"lang\": \"en\", \"theme\": \"c\"} elif lang == \"en_animals\" or",
"return {\"lang\": \"de\", \"theme\": \"a\"} elif lang == \"es\" or",
"of charge, to any person obtaining a copy of this",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS",
"\"it\", \"theme\": \"c\"} elif lang == \"it_animals\" or lang ==",
"or lang == \"korean\": return {\"lang\": \"kr\", \"theme\": \"c\"} elif",
"\"probably not\" OR \"pn\" OR \"4\" for PROBABLY NOT \"\"\".format(ans))",
"THE SOFTWARE. \"\"\" from .exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut,",
"Permission is hereby granted, free of charge, to any person",
"elif lang == \"il\" or lang == \"hebrew\": return {\"lang\":",
"\"it_animals\" or lang == \"italian_animals\": return {\"lang\": \"it\", \"theme\": \"a\"}",
"a different language\") elif response == \"KO - TIMEOUT\": raise",
"elif response == \"KO - TECHNICAL ERROR\": raise AkiTechnicalError(\"Akinator's servers",
"\"\"\"Returns the language code and theme based on what is",
"\"es_animals\" or lang == \"spanish_animals\": return {\"lang\": \"es\", \"theme\": \"a\"}",
"== \"polish\": return {\"lang\": \"pl\", \"theme\": \"c\"} elif lang ==",
"== \"german\": return {\"lang\": \"de\", \"theme\": \"c\"} elif lang ==",
"or lang == \"spanish\": return {\"lang\": \"es\", \"theme\": \"c\"} elif",
"\"KO - SERVER DOWN\": raise AkiServerDown(\"Akinator's servers are down in",
"\"theme\": \"c\"} elif lang == \"ru\" or lang == \"russian\":",
"\"en\", \"theme\": \"c\"} elif lang == \"en_animals\" or lang ==",
"or ans == \"i don't know\" or ans == \"2\":",
"or lang == \"german\": return {\"lang\": \"de\", \"theme\": \"c\"} elif",
"\"fr_objects\" or lang == \"french_objects\": return {\"lang\": \"fr\", \"theme\": \"o\"}",
"The above copyright notice and this permission notice shall be",
"dont know\" or ans == \"i don't know\" or ans",
"or lang == \"arabic\": return {\"lang\": \"ar\", \"theme\": \"c\"} elif",
"if the API failed to connect\"\"\" if response == \"KO",
"reached 80. No more questions\") else: raise AkiConnectionFailure(\"An unknown error",
"lang == \"french_animals\": return {\"lang\": \"fr\", \"theme\": \"a\"} elif lang",
"\"\"\" from .exceptions import InvalidAnswerError, InvalidLanguageError, AkiConnectionFailure, AkiTimedOut, AkiNoQuestions, AkiServerDown,",
"elif lang == \"cn\" or lang == \"chinese\": return {\"lang\":",
"had a technical error. Try again later or use a",
"== \"turkish\": return {\"lang\": \"tr\", \"theme\": \"c\"} else: raise InvalidLanguageError(\"You",
"return {\"lang\": \"nl\", \"theme\": \"c\"} elif lang == \"pl\" or",
"AkiTechnicalError(\"Akinator's servers have had a technical error. Try again later",
"\"spanish\": return {\"lang\": \"es\", \"theme\": \"c\"} elif lang == \"es_animals\"",
"language.\".format(lang)) def raise_connection_error(response): \"\"\"Raise the proper error if the API",
"raise InvalidAnswerError(\"\"\" You put \"{}\", which is an invalid answer.",
"\"fr\" or lang == \"french\": return {\"lang\": \"fr\", \"theme\": \"c\"}",
"== \"french\": return {\"lang\": \"fr\", \"theme\": \"c\"} elif lang ==",
"associated documentation files (the \"Software\"), to deal in the Software",
"ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION",
"== \"p\" or ans == \"3\": return \"3\" elif ans",
"return {\"lang\": \"es\", \"theme\": \"c\"} elif lang == \"es_animals\" or",
"THE USE OR OTHER DEALINGS IN THE SOFTWARE. \"\"\" from",
"ans == \"yes\" or ans == \"y\" or ans ==",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"\"japanese_animals\": return {\"lang\": \"jp\", \"theme\": \"a\"} elif lang == \"kr\"",
"else: raise InvalidAnswerError(\"\"\" You put \"{}\", which is an invalid"
] |
[
"(@movinalot) Cisco Systems, Inc. \"\"\" from ucsmsdk.ucshandle import UcsHandle from",
"= LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\" ) HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit() HANDLE.logout()",
"github: (@movinalot) Cisco Systems, Inc. \"\"\" from ucsmsdk.ucshandle import UcsHandle",
"Cisco Systems, Inc. \"\"\" from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer",
"OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login() ORG_ORG",
"UCS Service Profile Template Author: <NAME> (<EMAIL>) github: (@movinalot) Cisco",
"UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root',",
"Service Profile Template Author: <NAME> (<EMAIL>) github: (@movinalot) Cisco Systems,",
"ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" )",
"Create a UCS Service Profile Template Author: <NAME> (<EMAIL>) github:",
"UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE",
"<NAME> (<EMAIL>) github: (@movinalot) Cisco Systems, Inc. \"\"\" from ucsmsdk.ucshandle",
"import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg",
"\"password\" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG,",
"import OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login()",
"Inc. \"\"\" from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer",
"Profile Template Author: <NAME> (<EMAIL>) github: (@movinalot) Cisco Systems, Inc.",
"parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet',",
"<reponame>movinalot/ucs \"\"\" create_ucs_sp_template.py Purpose: UCS Manager Create a UCS Service",
"\"\"\" create_ucs_sp_template.py Purpose: UCS Manager Create a UCS Service Profile",
"= UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login() ORG_ORG = OrgOrg(",
"\"admin\", \"password\" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", )",
"name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\",",
") HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\"",
"Systems, Inc. \"\"\" from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import",
") HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True)",
"(<EMAIL>) github: (@movinalot) Cisco Systems, Inc. \"\"\" from ucsmsdk.ucshandle import",
"LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\",",
"HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login() ORG_ORG =",
"HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\" )",
"ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle(",
"HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit()",
"ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE",
"create_ucs_sp_template.py Purpose: UCS Manager Create a UCS Service Profile Template",
"\"\"\" from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from",
"Author: <NAME> (<EMAIL>) github: (@movinalot) Cisco Systems, Inc. \"\"\" from",
"UCS Manager Create a UCS Service Profile Template Author: <NAME>",
"Manager Create a UCS Service Profile Template Author: <NAME> (<EMAIL>)",
"from ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg",
"from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE =",
"OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer(",
"import LsServer from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\",",
"a UCS Service Profile Template Author: <NAME> (<EMAIL>) github: (@movinalot)",
"modify_present=True) HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\" ) HANDLE.add_mo(SP_TEMPLATE,",
"SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\" ) HANDLE.add_mo(SP_TEMPLATE, modify_present=True) HANDLE.commit()",
"\"sandbox-ucsm1.cisco.com\", \"admin\", \"password\" ) HANDLE.login() ORG_ORG = OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\",",
"Template Author: <NAME> (<EMAIL>) github: (@movinalot) Cisco Systems, Inc. \"\"\"",
"ucsmsdk.ucshandle import UcsHandle from ucsmsdk.mometa.ls.LsServer import LsServer from ucsmsdk.mometa.org.OrgOrg import",
"from ucsmsdk.mometa.org.OrgOrg import OrgOrg HANDLE = UcsHandle( \"sandbox-ucsm1.cisco.com\", \"admin\", \"password\"",
"= OrgOrg( parent_mo_or_dn='org-root', name=\"devnet\", ) HANDLE.add_mo(ORG_ORG, modify_present=True) HANDLE.commit() SP_TEMPLATE =",
"Purpose: UCS Manager Create a UCS Service Profile Template Author:",
"HANDLE.commit() SP_TEMPLATE = LsServer( parent_mo_or_dn='org-root/org-devnet', name=\"devcore_template\", type=\"updating-template\" ) HANDLE.add_mo(SP_TEMPLATE, modify_present=True)"
] |
[
"'test_runner_options', description='Additional command line options for tests run on AV',",
"AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of",
") VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console output', default=False )",
"QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False ) VERBOSE",
"description='Path to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString(",
"import pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable",
"documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less",
"after build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate",
"(.qrc) location', default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled",
"'qt', 'res_src', description='Qt resource file (.qrc) location', default='' ) QT_RES_TGT",
"file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional",
") QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource file",
"elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH =",
"'res_tgt', description='Compiled Qt resource file (.py) target location', default='' )",
"Twine after build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make',",
"'upload', description='Upload package to Twine after build', default=True, ) MAKE_GRAPH",
"elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list', element_type=str, default=[] ) DOC_REPO",
"'package_name', description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main",
"'lint', 'flake8_exclude', description='List of comma separated files for flake8 to",
"elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds for pytest runner', default=300",
"default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts",
"show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target',",
"= elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds for pytest runner',",
"'twine', 'upload', description='Upload package to Twine after build', default=True, )",
"logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml',",
"'freeze', 'data_files', description='PyInstaller data-files list', element_type=str, default=[] ) DOC_REPO =",
"TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to pass tests',",
"MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using PyReverse', default=True,",
"max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line width',",
"'data_files', description='PyInstaller data-files list', element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString(",
"'res_src', description='Qt resource file (.qrc) location', default='' ) QT_RES_TGT =",
") TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in",
"\"\"\" Handles EPAB's config file \"\"\" import logging import pathlib",
"= elib_config.ConfigValueBool( 'verbose', description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS =",
"elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of \"slow\" tests to show', default=10",
") MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using PyReverse',",
"'mypy_args', description='Additional MyPy arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt',",
"config file \"\"\" import logging import pathlib import elib_config CHANGELOG_DISABLE",
"'make', description='Generate graphs using PyReverse', default=True, ) def setup_config(epab_version: str):",
"description='Additional options for test run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger(",
"default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout",
"resource file (.qrc) location', default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt',",
"default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments',",
"= elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list', element_type=str, default=[] )",
"= elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to pass tests', default=20",
"= elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line width', default=120 )",
"package to Twine after build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool(",
"max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds for",
"on Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local",
"= elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze',",
"description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry",
"import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building',",
"to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test',",
"console output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional",
"DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory', default='./doc' )",
"width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package",
"for test run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count',",
"<reponame>132nd-etcher/epab # coding=utf-8 \"\"\" Handles EPAB's config file \"\"\" import",
"elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource file (.py) target location',",
"= elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog file', default='CHANGELOG.md' )",
"as as string \"\"\" logger = logging.getLogger('EPAB') logger.debug('setting up config')",
"'line_length', description='Linter max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME",
"arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource",
"elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments', default='' ) QT_RES_SRC =",
") def setup_config(epab_version: str): \"\"\" Set up elib_config package :param",
"in seconds for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH",
"file (.py) target location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine',",
"max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT =",
"elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on Github', default='' ) DOC_FOLDER",
"string \"\"\" logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB',",
"DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on Github', default=''",
") DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory', default='./doc'",
"description='Documentation repository on Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc',",
"for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude',",
"line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name',",
"Set up elib_config package :param epab_version: installed version of EPAB",
"description='Compiled Qt resource file (.py) target location', default='' ) UPLOAD_TO_TWINE",
"description='Qt resource file (.qrc) location', default='' ) QT_RES_TGT = elib_config.ConfigValueString(",
"'repo', description='Documentation repository on Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath(",
"'changelog', 'disable', description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath(",
"description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path',",
"pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files",
"elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False ) VERBOSE = elib_config.ConfigValueBool(",
"= logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__',",
"default=True, ) def setup_config(epab_version: str): \"\"\" Set up elib_config package",
"command line options for tests run on AV', default='--long' )",
"data-files list', element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo',",
"'qt', 'res_tgt', description='Compiled Qt resource file (.py) target location', default=''",
"'file_path', description='Path to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS =",
"description='Upload package to Twine after build', default=True, ) MAKE_GRAPH =",
") CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for",
"tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString(",
"package :param epab_version: installed version of EPAB as as string",
"MyPy arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt",
"run on AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts',",
") TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max",
"'freeze', 'entry_point', description='Main entry point for pyinstaller', default='' ) FREEZE_DATA_FILES",
"max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target of pytest', default='test'",
"'runner_options', description='Additional options for test run', default='' ) TEST_DURATION_COUNT =",
"= elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH",
"elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point for pyinstaller', default='' )",
"comma separated files for flake8 to exclude', default='' ) MYPY_ARGS",
"of \"slow\" tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET",
"elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma separated files for flake8",
"QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file (.qrc) location',",
"coding=utf-8 \"\"\" Handles EPAB's config file \"\"\" import logging import",
"build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs",
"= elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point for pyinstaller', default=''",
"default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using",
"element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository",
"elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to pass tests', default=20 )",
") FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point for",
":param epab_version: installed version of EPAB as as string \"\"\"",
"up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] )",
"ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts for Appveyor',",
"# coding=utf-8 \"\"\" Handles EPAB's config file \"\"\" import logging",
"description='List of artifacts for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE =",
"runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length',",
"Qt resource file (.py) target location', default='' ) UPLOAD_TO_TWINE =",
"default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name'",
"elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if",
"PyReverse', default=True, ) def setup_config(epab_version: str): \"\"\" Set up elib_config",
"for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger(",
"to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test',",
"PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString(",
"= elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource file (.py) target",
"'timeout', description='Timeout in seconds for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0,",
"description='Linter max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME =",
"FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list', element_type=str, default=[]",
"options for test run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test',",
"= elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to Twine after build',",
"default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console output',",
"location', default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt",
"tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout',",
"elib_config.ConfigValueString( 'test', 'target', description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER =",
"TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target of pytest', default='test' )",
"elib_config.ConfigValueBool( 'verbose', description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString(",
"= elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for test run', default=''",
"name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point",
"'test', 'duration_count', description='Amount of \"slow\" tests to show', default=10 )",
"default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console output', default=False",
"point for pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files',",
"app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not",
"= elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using PyReverse', default=True, )",
"root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not pathlib.Path('pyproject.toml').exists(): raise FileNotFoundError('pyproject.toml') elib_config.validate_config()",
"elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to Twine after build', default=True,",
"'test', 'coverage_fail_under', description='Minimal coverage to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0,",
"TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line",
"QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource file (.py)",
") LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name' )",
"config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not pathlib.Path('pyproject.toml').exists(): raise",
"elib_config.ConfigValueBool( 'graph', 'make', description='Generate graphs using PyReverse', default=True, ) def",
"setup_config(epab_version: str): \"\"\" Set up elib_config package :param epab_version: installed",
"default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options",
"\"\"\" logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version,",
"line options for tests run on AV', default='--long' ) ARTIFACTS",
"description='Timeout in seconds for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600)",
"'entry_point', description='Main entry point for pyinstaller', default='' ) FREEZE_DATA_FILES =",
"default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog",
") MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments', default=''",
"epab_version: installed version of EPAB as as string \"\"\" logger",
"def setup_config(epab_version: str): \"\"\" Set up elib_config package :param epab_version:",
"\"\"\" import logging import pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool(",
"= elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line options for tests",
"pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint',",
"Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List",
"'changelog', 'file_path', description='Path to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS",
"to Twine after build', default=True, ) MAKE_GRAPH = elib_config.ConfigValueBool( 'graph',",
"on AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List",
"config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not pathlib.Path('pyproject.toml').exists(): raise FileNotFoundError('pyproject.toml')",
"default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma",
"(.py) target location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload',",
"TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target of pytest',",
"app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example') if not pathlib.Path('pyproject.toml').exists():",
"files for flake8 to exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString(",
"console output', default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console",
") FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma separated",
"of EPAB as as string \"\"\" logger = logging.getLogger('EPAB') logger.debug('setting",
"default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter",
"default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory',",
"'target', description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test',",
"coverage to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT =",
"description='Additional command line options for tests run on AV', default='--long'",
") CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog file',",
"'test', 'runner_options', description='Additional options for test run', default='' ) TEST_DURATION_COUNT",
"default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of \"slow\"",
"elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0,",
"str): \"\"\" Set up elib_config package :param epab_version: installed version",
"default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to",
"as string \"\"\" logger = logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup(",
"'lint', 'mypy_args', description='Additional MyPy arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString(",
"description='Additional MyPy arguments', default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src',",
"LINT_LINE_LENGTH = elib_config.ConfigValueInteger( 'lint', 'line_length', description='Linter max line width', default=120",
") QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file (.qrc)",
"tests run on AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList( 'appveyor',",
") FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list', element_type=str,",
"logging.getLogger('EPAB') logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool',",
"target location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload",
"of artifacts for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString(",
"default='' ) QT_RES_SRC = elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file",
"CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building', default=False )",
"'quiet', description='Less console output', default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose',",
"elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file()",
") TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to pass",
"repository on Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder',",
"logging import pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable',",
"'coverage_fail_under', description='Minimal coverage to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100)",
"description='Generate graphs using PyReverse', default=True, ) def setup_config(epab_version: str): \"\"\"",
"LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT",
") DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on Github',",
"TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of \"slow\" tests to",
"list', element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation",
"building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to",
"entry point for pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze',",
"description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet',",
"EPAB as as string \"\"\" logger = logging.getLogger('EPAB') logger.debug('setting up",
"of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal",
"description='List of comma separated files for flake8 to exclude', default=''",
"file (.qrc) location', default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt',",
"'disable', description='Disable changelog building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog',",
"TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds",
"'artifacts', description='List of artifacts for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE",
"description='Main entry point for pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList(",
"EPAB's config file \"\"\" import logging import pathlib import elib_config",
"VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS",
"'appveyor', 'test_runner_options', description='Additional command line options for tests run on",
") ARTIFACTS = elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts for",
"'doc', 'folder', description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET =",
"= elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma separated files for",
"options for tests run on AV', default='--long' ) ARTIFACTS =",
"'verbose', description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor',",
"default='' ) QT_RES_TGT = elib_config.ConfigValueString( 'qt', 'res_tgt', description='Compiled Qt resource",
"= elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir()",
"default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage to",
"output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command",
"elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET",
"up elib_config package :param epab_version: installed version of EPAB as",
"'test', 'timeout', description='Timeout in seconds for pytest runner', default=300 )",
"elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for test run', default='' )",
"directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console",
"changelog building', default=False ) CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path",
"element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of",
"changelog file', default='CHANGELOG.md' ) CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options',",
"for tests run on AV', default='--long' ) ARTIFACTS = elib_config.ConfigValueList(",
") TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line options",
"logger.debug('setting up config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab']",
"default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller data-files list',",
"TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test', 'timeout', description='Timeout in seconds for pytest",
"of comma separated files for flake8 to exclude', default='' )",
") TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of \"slow\" tests",
"elib_config.ConfigValueString( 'package_name', description='Package name' ) FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point',",
"= elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of \"slow\" tests to show',",
"FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint', 'flake8_exclude', description='List of comma separated files",
"import logging import pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog',",
"elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file (.qrc) location', default='' )",
"version of EPAB as as string \"\"\" logger = logging.getLogger('EPAB')",
"CHANGELOG_FILE_PATH.must_be_file() TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for test",
"= elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments', default='' ) QT_RES_SRC",
") TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target of",
"'folder', description='Local documentation directory', default='./doc' ) DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool(",
"= elib_config.ConfigValueString( 'test', 'target', description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER",
"Handles EPAB's config file \"\"\" import logging import pathlib import",
"TEST_RUNNER_OPTIONS = elib_config.ConfigValueString( 'test', 'runner_options', description='Additional options for test run',",
"= elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts for Appveyor', element_type=str,",
"\"slow\" tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET =",
"TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line options for",
"to exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional",
"for flake8 to exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint',",
"MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy arguments', default='' )",
"= elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on Github', default='' )",
"seconds for pytest runner', default=300 ) TEST_PYTEST_TIMEOUT.set_limits(min_=0, max_=3600) LINT_LINE_LENGTH =",
"max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500) PACKAGE_NAME = elib_config.ConfigValueString(",
"Github', default='' ) DOC_FOLDER = elib_config.ConfigValuePath( 'doc', 'folder', description='Local documentation",
") UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to Twine",
"pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger( 'test',",
"pathlib import elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog",
"flake8 to exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args',",
"pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under', description='Minimal coverage",
"resource file (.py) target location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool(",
"default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50) TEST_TARGET = elib_config.ConfigValueString( 'test', 'target', description='Target",
"elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line options for tests run",
"'duration_count', description='Amount of \"slow\" tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0,",
"= elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False ) VERBOSE =",
"using PyReverse', default=True, ) def setup_config(epab_version: str): \"\"\" Set up",
"run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount of",
"CHANGELOG_FILE_PATH = elib_config.ConfigValuePath( 'changelog', 'file_path', description='Path to changelog file', default='CHANGELOG.md'",
"description='More console output', default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options',",
"test run', default='' ) TEST_DURATION_COUNT = elib_config.ConfigValueInteger( 'test', 'duration_count', description='Amount",
"config') elib_config.ELIBConfig.setup( app_name='EPAB', app_version=epab_version, config_file_path='pyproject.toml', config_sep_str='__', root_path=['tool', 'epab'] ) elib_config.write_example_config('pyproject.toml.example')",
"elib_config package :param epab_version: installed version of EPAB as as",
"FREEZE_ENTRY_POINT = elib_config.ConfigValueString( 'freeze', 'entry_point', description='Main entry point for pyinstaller',",
"for pyinstaller', default='' ) FREEZE_DATA_FILES = elib_config.ConfigValueList( 'freeze', 'data_files', description='PyInstaller",
"elib_config.ConfigValueList( 'appveyor', 'artifacts', description='List of artifacts for Appveyor', element_type=str, default=[]",
"output', default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More console output',",
"description='PyInstaller data-files list', element_type=str, default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc',",
"exclude', default='' ) MYPY_ARGS = elib_config.ConfigValueString( 'lint', 'mypy_args', description='Additional MyPy",
"to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT = elib_config.ConfigValueInteger(",
"UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package to Twine after",
"artifacts for Appveyor', element_type=str, default=[] ) FLAKE8_EXCLUDE = elib_config.ConfigValueString( 'lint',",
"'doc', 'repo', description='Documentation repository on Github', default='' ) DOC_FOLDER =",
"location', default='' ) UPLOAD_TO_TWINE = elib_config.ConfigValueBool( 'twine', 'upload', description='Upload package",
"graphs using PyReverse', default=True, ) def setup_config(epab_version: str): \"\"\" Set",
"elib_config CHANGELOG_DISABLE = elib_config.ConfigValueBool( 'changelog', 'disable', description='Disable changelog building', default=False",
"= elib_config.ConfigValueString( 'qt', 'res_src', description='Qt resource file (.qrc) location', default=''",
"default=[] ) DOC_REPO = elib_config.ConfigValueString( 'doc', 'repo', description='Documentation repository on",
") DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False",
"'flake8_exclude', description='List of comma separated files for flake8 to exclude',",
"description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger( 'test', 'coverage_fail_under',",
"default=False ) TEST_AV_RUNNER_OPTIONS = elib_config.ConfigValueString( 'appveyor', 'test_runner_options', description='Additional command line",
"description='Less console output', default=False ) VERBOSE = elib_config.ConfigValueBool( 'verbose', description='More",
"file \"\"\" import logging import pathlib import elib_config CHANGELOG_DISABLE =",
"'graph', 'make', description='Generate graphs using PyReverse', default=True, ) def setup_config(epab_version:",
"DOC_FOLDER.must_be_dir() QUIET = elib_config.ConfigValueBool( 'quiet', description='Less console output', default=False )",
"description='Amount of \"slow\" tests to show', default=10 ) TEST_DURATION_COUNT.set_limits(min_=0, max_=50)",
"'test', 'target', description='Target of pytest', default='test' ) TEST_COVERAGE_FAIL_UNDER = elib_config.ConfigValueInteger(",
"description='Minimal coverage to pass tests', default=20 ) TEST_COVERAGE_FAIL_UNDER.set_limits(min_=0, max_=100) TEST_PYTEST_TIMEOUT",
"separated files for flake8 to exclude', default='' ) MYPY_ARGS =",
"\"\"\" Set up elib_config package :param epab_version: installed version of",
"installed version of EPAB as as string \"\"\" logger =",
"'lint', 'line_length', description='Linter max line width', default=120 ) LINT_LINE_LENGTH.set_limits(min_=0, max_=500)",
"'appveyor', 'artifacts', description='List of artifacts for Appveyor', element_type=str, default=[] )"
] |
[
"%I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable unneeded dependencies logging\", \"werkzeugLog =",
"ep) tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for",
"'request_endpoints': request_endpoints } if __name__ == '__main__': parser = argparse.ArgumentParser()",
"params[param]: for line in headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']:",
"param in params.keys(): if params[param] and param != 'app': print(param,",
"args[param] else: params[param] = args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css'",
"params['threading']: for line in [\"\", \"#Thread\", \"def keep_alive():\", \"\\tt =",
"' app succesfully.') for param in params.keys(): if params[param] and",
"+ request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method",
"+ pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None,",
"None: params[param] = args[param] else: params[param] = args[param] index =",
"' + ep, '\\nMethod: ' + request_method, '\\nParameter: ' +",
"keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line in [\"\",",
"= args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project",
"[\"\", \"#Disable unneeded dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled =",
"endpoints=None, request_endpoints=None): check_for_pkg('flask') lines = [\"from flask import Flask, send_from_directory\",\"import",
"ep, request_param in request_endpoints: print('Endpoint: ' + ep, '\\nMethod: '",
"- 1) // 3)] for request_method, ep, request_param in request_endpoints:",
"site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints } if __name__ == '__main__':",
"\"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line in tp: lines.append(line.replace('endpoint', ep))",
"warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import logging\", \"\", \"#Logging configuration",
"for param in args.keys(): if 'request' in param and len(args[param])",
"in [\"\", \"#Thread\", \"def keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line)",
"threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines",
"for param in params.keys(): if 'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(),",
"further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines = [\"from flask import",
"if 'request' in param and len(args[param]) % 3 != 0:",
"f.write(line+'\\n') f.close() print('Created' + project + ' app succesfully.') for",
"os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close()",
"\"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import warnings\",",
"\"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled",
"debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\",",
"not None: for ep in site_endpoints: print('Endpoint: ' + ep)",
"\"Method\" \"Endpoint\" \"Parameter\"') if param == 'app': if args[param] !=",
"endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line in tp:",
"params['site_endpoints'] if site_endpoints is not None: for ep in site_endpoints:",
"\"\\treturn do_something(\"+request_param+\")\"] for line in tp: lines.append(line) lines.append(\"\\nif __name__ ==",
"def check_for_pkg(pkg): try: exec(\"import \" + pkg) except: os.system(\"pip3 install",
"'r', 'utf-8').read()\"] for line in tp: lines.append(line.replace('endpoint', ep)) epFile =",
"[\"\", \"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\",",
"threading import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"],",
"for ep in site_endpoints: print('Endpoint: ' + ep) tp =",
"epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints",
"lines.append(\"\\trun()\") for line in lines: f.write(line+'\\n') f.close() print('Created' + project",
"if endpoints is not None: for ep in endpoints: print('Endpoint:",
"lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js'))",
"'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints } if __name__ ==",
"file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable",
"and len(args[param]) % 3 != 0: print('Request method endpoint format",
"'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\",",
"datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable unneeded dependencies logging\", \"werkzeugLog",
"required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args = vars(parser.parse_args()) for",
"\"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], } for param in",
"format invalid, enter \"Method\" \"Endpoint\" \"Parameter\"') if param == 'app':",
"check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for",
"if params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\")",
"install --user \" + pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False,",
"\"from threading import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi import",
"\"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\",",
"= [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for",
"= params['site_endpoints'] if site_endpoints is not None: for ep in",
"\"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line in tp: lines.append(line.replace('endpoint',",
"indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers",
"method endpoint format invalid, enter \"Method\" \"Endpoint\" \"Parameter\"') if param",
"check_for_pkg('flask') lines = [\"from flask import Flask, send_from_directory\",\"import codecs\", \"import",
"print('Request method endpoint format invalid, enter \"Method\" \"Endpoint\" \"Parameter\"') if",
"endpoint format invalid, enter \"Method\" \"Endpoint\" \"Parameter\"') if param ==",
"tp: lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js',",
"[\"\", \"#Logging\", \"import logging\", \"\", \"#Logging configuration set to debug",
"'+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if endpoints is not None: for",
"logging\", \"\", \"#Logging configuration set to debug on debug.log file\",",
"app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line in [\"\", \"#Thread\",",
"parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False)",
"'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable",
"lines: f.write(line+'\\n') f.close() print('Created' + project + ' app succesfully.')",
"line in headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\")",
"params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']:",
"os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js')",
"'app': app, 'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging,",
"site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines = [\"from flask import Flask,",
"// 3)] for request_method, ep, request_param in request_endpoints: print('Endpoint: '",
"'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints,",
"= [request_endpoints[i * 3:(i + 1) * 3] for i",
"' + request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\"",
"'further_logging': [\"\", \"#Disable unneeded dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled",
"set to debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y",
"% 3 != 0: print('Request method endpoint format invalid, enter",
"indexFile.write(index.replace('endpoint', project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers = { 'threading':",
"print(request_endpoints) request_method = request_endpoints[0] if request_endpoints is not None: request_endpoints",
"else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line in [\"\", \"#Thread\", \"def",
"tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn",
"send_from_directory\",\"import codecs\", \"import os\"] params = { 'app': app, 'threading':",
"3 != 0: print('Request method endpoint format invalid, enter \"Method\"",
"headers = { 'threading': [\"\", \"#Threading\", \"from threading import Thread\"],",
"headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081),",
"\"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line in tp: lines.append(line.replace('endpoint',",
"codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line in tp: lines.append(line.replace('endpoint', ep)) epFile",
"parser = argparse.ArgumentParser() for param in params.keys(): if 'endpoints' in",
"param != 'app': print(param, params[param]) os.system('open '+ project) if __name__",
"os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if endpoints is",
"request_method, '\\nParameter: ' + request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def",
"ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if",
"os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f =",
"open(project+'/'+project+\".py\",\"w+\") headers = { 'threading': [\"\", \"#Threading\", \"from threading import",
"8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line in [\"\",",
"in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(),",
"'logging': [\"\", \"#Logging\", \"import logging\", \"\", \"#Logging configuration set to",
"lines.append(\"\\nif __name__ == '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\")",
"endpoints, 'request_endpoints': request_endpoints } if __name__ == '__main__': parser =",
"lines.append(line) for line in [\"\", \"app = Flask(__name__)\", \"\", \"@app.route('/')\",",
"* 3:(i + 1) * 3] for i in range((len(request_endpoints)",
"lines.append(line) site_endpoints = params['site_endpoints'] if site_endpoints is not None: for",
"\"app = Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html',",
"lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line",
"[\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line in tp:",
"[\"\", \"app = Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn",
"endpoints is not None: for ep in endpoints: print('Endpoint: '",
"'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging': further_logging,",
"\"\\treturn endpoint_route\"] for line in tp: lines.append(line.replace('endpoint', ep)) request_endpoints =",
"logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints }",
"\"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line in",
"lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line in",
"logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\",",
"params[param] and param != 'app': print(param, params[param]) os.system('open '+ project)",
"params[param] = args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\"",
"\"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints']",
"3)] for request_method, ep, request_param in request_endpoints: print('Endpoint: ' +",
"None: request_endpoints = [request_endpoints[i * 3:(i + 1) * 3]",
"= \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if",
"+ ep) tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"]",
"'+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\")",
"'__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\")",
"[\"from flask import Flask, send_from_directory\",\"import codecs\", \"import os\"] params =",
"+ 1) * 3] for i in range((len(request_endpoints) + 3",
"print('Endpoint: ' + ep, '\\nMethod: ' + request_method, '\\nParameter: '",
"lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\")",
"\"werkzeugLog.disabled = True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], }",
"request_endpoints[0] if request_endpoints is not None: request_endpoints = [request_endpoints[i *",
"open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers = {",
"unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines = [\"from",
"further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints } if __name__",
"= True\"], } for param in headers.keys(): if params[param]: for",
"request_param in request_endpoints: print('Endpoint: ' + ep, '\\nMethod: ' +",
"== '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run",
"'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints'] if site_endpoints is not",
"\"#Logging configuration set to debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s",
"True\"], } for param in headers.keys(): if params[param]: for line",
"print(param, params[param]) os.system('open '+ project) if __name__ == '__main__': create_flask_app()",
"\"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line in tp:",
"flask import Flask, send_from_directory\",\"import codecs\", \"import os\"] params = {",
"+ ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html',",
"{ 'app': app, 'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging':",
"\"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints =",
"\"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints'] if site_endpoints",
"= args[param] else: params[param] = args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link",
"os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static')",
"--user \" + pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False,",
"for i in range((len(request_endpoints) + 3 - 1) // 3)]",
"in headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('',",
"if params[param] and param != 'app': print(param, params[param]) os.system('open '+",
"'app': print(param, params[param]) os.system('open '+ project) if __name__ == '__main__':",
"in [\"\", \"app = Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\",",
"'threading': [\"\", \"#Threading\", \"from threading import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\",",
"\"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn",
"'\\nMethod: ' + request_method, '\\nParameter: ' + request_param) tp =",
"'+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if endpoints is not",
"\"import logging\", \"\", \"#Logging configuration set to debug on debug.log",
"= { 'app': app, 'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings,",
"'utf-8').read()\"] for line in tp: lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint',",
"vars(parser.parse_args()) for param in args.keys(): if 'request' in param and",
"\"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line in tp: lines.append(line)",
"lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0] if",
"os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project))",
"\"requestsLog.disabled = True\"], } for param in headers.keys(): if params[param]:",
"tp: lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0]",
"wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints':",
"codecs\", \"import os\"] params = { 'app': app, 'threading': threading,",
"= [\"from flask import Flask, send_from_directory\",\"import codecs\", \"import os\"] params",
"pkg) except: os.system(\"pip3 install --user \" + pkg) def create_flask_app(app='flask_app',",
"method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line in tp: lines.append(line) lines.append(\"\\nif",
"rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if not os.path.exists(project): os.mkdir(project) if",
"\"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\",",
"None: for ep in site_endpoints: print('Endpoint: ' + ep) tp",
"= open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers =",
"argparse def check_for_pkg(pkg): try: exec(\"import \" + pkg) except: os.system(\"pip3",
"configuration set to debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s',",
"for param in headers.keys(): if params[param]: for line in headers[param]:",
"[\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line",
"= params['app'] if not os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web')",
"params['app'] if not os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if",
"\"\\tt.start()\"]: lines.append(line) for line in [\"\", \"app = Flask(__name__)\", \"\",",
"run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\")",
"help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args = vars(parser.parse_args())",
"to debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S",
"indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers = { 'threading': [\"\", \"#Threading\",",
"= params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0] if request_endpoints is not",
"invalid, enter \"Method\" \"Endpoint\" \"Parameter\"') if param == 'app': if",
"if not os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not",
"not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch",
"do_something(\"+request_param+\")\"] for line in tp: lines.append(line) lines.append(\"\\nif __name__ == '__main__':\")",
"in args.keys(): if 'request' in param and len(args[param]) % 3",
"ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints =",
"dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog =",
"def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None):",
"\"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints",
"\"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable unneeded",
"Flask, send_from_directory\",\"import codecs\", \"import os\"] params = { 'app': app,",
"os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint',",
"= logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled =",
"\"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line in tp: lines.append(line.replace('endpoint', ep)) request_endpoints",
"ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js')",
"lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line in lines: f.write(line+'\\n')",
"on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging':",
"endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line in tp: lines.append(line.replace('endpoint', ep))",
"src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if not os.path.exists(project): os.mkdir(project) if not",
"import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging':",
"epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if endpoints",
"Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import logging\", \"\",",
"params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for",
"'\\nParameter: ' + request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\",",
"0: print('Request method endpoint format invalid, enter \"Method\" \"Endpoint\" \"Parameter\"')",
"not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\")",
"logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"],",
"param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='',",
"\"#Thread\", \"def keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line",
"' + ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn",
"project = params['app'] if not os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'):",
"if 'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False) else:",
"= logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], } for param in headers.keys():",
"params[param] = args[param] else: params[param] = args[param] index = \"<!DOCTYPE",
"codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico',",
"!= 'app': print(param, params[param]) os.system('open '+ project) if __name__ ==",
"tp: lines.append(line) lines.append(\"\\nif __name__ == '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server",
"is not None: for ep in endpoints: print('Endpoint: ' +",
"import argparse def check_for_pkg(pkg): try: exec(\"import \" + pkg) except:",
"site_endpoints is not None: for ep in site_endpoints: print('Endpoint: '",
"threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging': further_logging, 'site_endpoints':",
"parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args = vars(parser.parse_args()) for param in",
"site_endpoints = params['site_endpoints'] if site_endpoints is not None: for ep",
"main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\",",
"lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line",
"param in headers.keys(): if params[param]: for line in headers[param]: lines.append(line)",
"+ ' app succesfully.') for param in params.keys(): if params[param]",
"server\") lines.append(\"\\trun()\") for line in lines: f.write(line+'\\n') f.close() print('Created' +",
"<gh_stars>1-10 import os import argparse def check_for_pkg(pkg): try: exec(\"import \"",
"index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app']",
"} for param in headers.keys(): if params[param]: for line in",
"'logging': logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints",
"endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line in tp: lines.append(line) lines.append(\"\\nif __name__",
"\" + pkg) except: os.system(\"pip3 install --user \" + pkg)",
"+ 3 - 1) // 3)] for request_method, ep, request_param",
"os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints'] if endpoints is not None:",
"params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0] if request_endpoints is not None:",
"in site_endpoints: print('Endpoint: ' + ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def",
"lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else:",
"for request_method, ep, request_param in request_endpoints: print('Endpoint: ' + ep,",
"in params.keys(): if params[param] and param != 'app': print(param, params[param])",
"not os.path.exists(project): os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'):",
"\"Parameter\"') if param == 'app': if args[param] != None: params[param]",
"param and len(args[param]) % 3 != 0: print('Request method endpoint",
"\"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import logging\",",
"= params['endpoints'] if endpoints is not None: for ep in",
"else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line in lines: f.write(line+'\\n') f.close()",
"request_method = request_endpoints[0] if request_endpoints is not None: request_endpoints =",
"1) * 3] for i in range((len(request_endpoints) + 3 -",
"for line in lines: f.write(line+'\\n') f.close() print('Created' + project +",
"logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], } for param in headers.keys(): if",
"os\"] params = { 'app': app, 'threading': threading, 'wsgiserver': wsgiserver,",
"import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings':",
"print('Endpoint: ' + ep) tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\",",
"= [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"]",
"if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css')",
"= Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line in [\"\", \"app =",
"print('Created' + project + ' app succesfully.') for param in",
"3 - 1) // 3)] for request_method, ep, request_param in",
"not None: request_endpoints = [request_endpoints[i * 3:(i + 1) *",
"\"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line in [\"\", \"app",
"check_for_pkg(pkg): try: exec(\"import \" + pkg) except: os.system(\"pip3 install --user",
"lines = [\"from flask import Flask, send_from_directory\",\"import codecs\", \"import os\"]",
"+ pkg) except: os.system(\"pip3 install --user \" + pkg) def",
"favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints'] if",
"logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines = [\"from flask",
"args = vars(parser.parse_args()) for param in args.keys(): if 'request' in",
"endpoints: print('Endpoint: ' + ep) tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\",",
"enter \"Method\" \"Endpoint\" \"Parameter\"') if param == 'app': if args[param]",
"+ project + ' app succesfully.') for param in params.keys():",
"href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if not os.path.exists(project): os.mkdir(project)",
"request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\",",
"'+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile = open(project+\"/web/index.html\",\"w+\") indexFile.write(index.replace('endpoint', project)) indexFile.close() f",
"ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r',",
"!= None: params[param] = args[param] else: params[param] = args[param] index",
"methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for line",
"args.keys(): if 'request' in param and len(args[param]) % 3 !=",
"%p')\"], 'further_logging': [\"\", \"#Disable unneeded dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\",",
"'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints,",
"= request_endpoints[0] if request_endpoints is not None: request_endpoints = [request_endpoints[i",
"request_endpoints = [request_endpoints[i * 3:(i + 1) * 3] for",
"os import argparse def check_for_pkg(pkg): try: exec(\"import \" + pkg)",
"if args[param] != None: params[param] = args[param] else: params[param] =",
"debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\", \"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"],",
"unneeded dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\", \"requestsLog",
"' + ep) tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn",
"f = open(project+'/'+project+\".py\",\"w+\") headers = { 'threading': [\"\", \"#Threading\", \"from",
"== 'app': if args[param] != None: params[param] = args[param] else:",
"os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile",
"import Flask, send_from_directory\",\"import codecs\", \"import os\"] params = { 'app':",
"request_endpoints } if __name__ == '__main__': parser = argparse.ArgumentParser() for",
"params['endpoints'] if endpoints is not None: for ep in endpoints:",
"tp = [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line",
"params = { 'app': app, 'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings':",
"\"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if not",
"for line in [\"\", \"#Thread\", \"def keep_alive():\", \"\\tt = Thread(target=run)\",",
"True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], } for param",
"request_endpoints = params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0] if request_endpoints is",
"in tp: lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css',",
"line in [\"\", \"#Thread\", \"def keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]:",
"+ request_method, '\\nParameter: ' + request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\",",
"nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args =",
"param in params.keys(): if 'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+',",
"and param != 'app': print(param, params[param]) os.system('open '+ project) if",
"if site_endpoints is not None: for ep in site_endpoints: print('Endpoint:",
"ep in site_endpoints: print('Endpoint: ' + ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\",",
"for ep in endpoints: print('Endpoint: ' + ep) tp =",
"\"#Disable unneeded dependencies logging\", \"werkzeugLog = logging.getLogger('werkzeug')\", \"werkzeugLog.disabled = True\",",
"[\"\", \"#Thread\", \"def keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for",
"if params[param]: for line in headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if",
"wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask') lines =",
"exec(\"import \" + pkg) except: os.system(\"pip3 install --user \" +",
"open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch",
"os.mkdir(project) if not os.path.exists(project+'/web'): os.mkdir(project+'/web') if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch",
"__name__ == '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server forever\") lines.append(\"\\tkeep_alive()\") else:",
"line in lines: f.write(line+'\\n') f.close() print('Created' + project + '",
"headers.keys(): if params[param]: for line in headers[param]: lines.append(line) lines.append(\"\\ndef run():\")",
"WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\",",
"in param and len(args[param]) % 3 != 0: print('Request method",
"pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None,",
"for param in params.keys(): if params[param] and param != 'app':",
"3] for i in range((len(request_endpoints) + 3 - 1) //",
"\"logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable unneeded dependencies",
"range((len(request_endpoints) + 3 - 1) // 3)] for request_method, ep,",
"forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line in lines:",
"line in [\"\", \"app = Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\",",
"'app': if args[param] != None: params[param] = args[param] else: params[param]",
"args[param] != None: params[param] = args[param] else: params[param] = args[param]",
"[\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">', methods=['\"+request_method+\"'])\", \"def \"+ep+\"(\"+request_param+\"):\", \"\\t#\"+request_method+\" method endpoint\", \"\\treturn do_something(\"+request_param+\")\"] for",
"Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\",",
"ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close()",
"else: params[param] = args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script",
"gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"],",
"len(args[param]) % 3 != 0: print('Request method endpoint format invalid,",
"is not None: for ep in site_endpoints: print('Endpoint: ' +",
"'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line)",
"= Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r',",
"import os import argparse def check_for_pkg(pkg): try: exec(\"import \" +",
"= vars(parser.parse_args()) for param in args.keys(): if 'request' in param",
"help='', required=False) args = vars(parser.parse_args()) for param in args.keys(): if",
"argparse.ArgumentParser() for param in params.keys(): if 'endpoints' in param: parser.add_argument('-'+param[0].lower(),",
"\"#WSGIServer\", \"from gevent.pywsgi import WSGIServer\"], 'unwanted_warnings': [\"\", \"#Disable Warnings\", \"import",
"\"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def",
"Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line in [\"\", \"app = Flask(__name__)\",",
"line in tp: lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint',",
"None: for ep in endpoints: print('Endpoint: ' + ep) tp",
"\"\", \"#Logging configuration set to debug on debug.log file\", \"logging.basicConfig(filename='debug.log',level=logging.DEBUG)\",",
"if params['threading']: for line in [\"\", \"#Thread\", \"def keep_alive():\", \"\\tt",
"in endpoints: print('Endpoint: ' + ep) tp = [\"\\n@app.route('/endpoint')\", \"def",
"mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints'] if site_endpoints is not None:",
"{ 'threading': [\"\", \"#Threading\", \"from threading import Thread\"], 'wsgiserver': [\"\",",
"param == 'app': if args[param] != None: params[param] = args[param]",
"\"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"] for line in",
"if not os.path.exists(project+'/static'): os.mkdir(project+'/static') os.system('touch '+project+'/static/style.css') os.system('touch '+project+'/static/script.js') indexFile =",
"not None: for ep in endpoints: print('Endpoint: ' + ep)",
"unwanted_warnings, 'logging': logging, 'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints':",
"ep, '\\nMethod: ' + request_method, '\\nParameter: ' + request_param) tp",
"'endpoints': endpoints, 'request_endpoints': request_endpoints } if __name__ == '__main__': parser",
"= open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css')",
"in lines: f.write(line+'\\n') f.close() print('Created' + project + ' app",
"\"def keep_alive():\", \"\\tt = Thread(target=run)\", \"\\tt.start()\"]: lines.append(line) for line in",
"'further_logging': further_logging, 'site_endpoints': site_endpoints, 'endpoints': endpoints, 'request_endpoints': request_endpoints } if",
"epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\") epFile.write(index.replace('endpoint', ep).replace('style.css', ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch",
"in range((len(request_endpoints) + 3 - 1) // 3)] for request_method,",
"in tp: lines.append(line) lines.append(\"\\nif __name__ == '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run",
"ep)) request_endpoints = params['request_endpoints'] print(request_endpoints) request_method = request_endpoints[0] if request_endpoints",
"= argparse.ArgumentParser() for param in params.keys(): if 'endpoints' in param:",
"' + request_method, '\\nParameter: ' + request_param) tp = [\"\\<EMAIL>('/\"+ep+\"/<\"+request_param+\">',",
"param in args.keys(): if 'request' in param and len(args[param]) %",
"in params.keys(): if 'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='',",
"html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project = params['app'] if not os.path.exists(project):",
"== '__main__': parser = argparse.ArgumentParser() for param in params.keys(): if",
"= True\", \"requestsLog = logging.getLogger('urllib3.connectionpool')\", \"requestsLog.disabled = True\"], } for",
"= { 'threading': [\"\", \"#Threading\", \"from threading import Thread\"], 'wsgiserver':",
"[\"\", \"#Threading\", \"from threading import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from",
"succesfully.') for param in params.keys(): if params[param] and param !=",
"\"import os\"] params = { 'app': app, 'threading': threading, 'wsgiserver':",
"required=False) args = vars(parser.parse_args()) for param in args.keys(): if 'request'",
"lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line in lines: f.write(line+'\\n') f.close() print('Created'",
"\" + pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False,",
"project)) indexFile.close() f = open(project+'/'+project+\".py\",\"w+\") headers = { 'threading': [\"\",",
"for line in headers[param]: lines.append(line) lines.append(\"\\ndef run():\") if params['wsgiserver']: check_for_pkg('gevent')",
"%(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')\"], 'further_logging': [\"\", \"#Disable unneeded dependencies logging\",",
"args[param] index = \"<!DOCTYPE html>\\n<html>\\n<head>\\n\\t<title>endpoint</title>\\n\\t<link href='static/style.css' rel='stylesheet'>\\n</head>\\n<body>\\n\\n<script src='static/script.js'></script>\\n</body>\\n</html>\" project =",
"'--'+param.lower(), help='', required=False) args = vars(parser.parse_args()) for param in args.keys():",
"else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args = vars(parser.parse_args()) for param",
"* 3] for i in range((len(request_endpoints) + 3 - 1)",
"lines.append(line) lines.append(\"\\nif __name__ == '__main__':\") if params['wsgiserver']: lines.append(\"\\t#Run server forever\")",
"__name__ == '__main__': parser = argparse.ArgumentParser() for param in params.keys():",
"!= 0: print('Request method endpoint format invalid, enter \"Method\" \"Endpoint\"",
"try: exec(\"import \" + pkg) except: os.system(\"pip3 install --user \"",
"'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]:",
"is not None: request_endpoints = [request_endpoints[i * 3:(i + 1)",
"f.close() print('Created' + project + ' app succesfully.') for param",
"1) // 3)] for request_method, ep, request_param in request_endpoints: print('Endpoint:",
"tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn codecs.open('web/endpoint.html', 'r', 'utf-8').read()\"]",
"os.system(\"pip3 install --user \" + pkg) def create_flask_app(app='flask_app', threading=False, wsgiserver=False,",
"params.keys(): if 'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False)",
"params.keys(): if params[param] and param != 'app': print(param, params[param]) os.system('open",
"ep+'.css').replace('script.js', ep+'.js')) epFile.close() os.system('touch '+project+'/static/'+ep+'.css') os.system('touch '+project+'/static/'+ep+'.js') endpoints = params['endpoints']",
"except: os.system(\"pip3 install --user \" + pkg) def create_flask_app(app='flask_app', threading=False,",
"line in tp: lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints'] print(request_endpoints) request_method",
"in request_endpoints: print('Endpoint: ' + ep, '\\nMethod: ' + request_method,",
"[request_endpoints[i * 3:(i + 1) * 3] for i in",
"'request' in param and len(args[param]) % 3 != 0: print('Request",
"site_endpoints: print('Endpoint: ' + ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\",",
"for line in tp: lines.append(line.replace('endpoint', ep)) epFile = open(project+\"/web/endpoint.html\".replace('endpoint', ep),\"w+\")",
"endpoint_route\"] for line in tp: lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints']",
"request_endpoints is not None: request_endpoints = [request_endpoints[i * 3:(i +",
"print('Endpoint: ' + ep) tp = [\"\\n@<EMAIL>.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\",",
"if params['wsgiserver']: check_for_pkg('gevent') lines.append(\"\\t#WSGIServer\") lines.append(\"\\tWSGIServer(('', 8081), app).serve_forever()\") else: lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if",
"i in range((len(request_endpoints) + 3 - 1) // 3)] for",
"app, 'threading': threading, 'wsgiserver': wsgiserver, 'unwanted_warnings': unwanted_warnings, 'logging': logging, 'further_logging':",
"'endpoints' in param: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(),",
"if __name__ == '__main__': parser = argparse.ArgumentParser() for param in",
"in tp: lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints'] print(request_endpoints) request_method =",
"app succesfully.') for param in params.keys(): if params[param] and param",
"for line in tp: lines.append(line.replace('endpoint', ep)) request_endpoints = params['request_endpoints'] print(request_endpoints)",
"for line in tp: lines.append(line) lines.append(\"\\nif __name__ == '__main__':\") if",
"\"#Logging\", \"import logging\", \"\", \"#Logging configuration set to debug on",
"\"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\", \"\", \"@app.route('/favicon.ico')\", \"def favicon():\", \"\\treturn send_from_directory(os.path.join(app.root_path,",
"} if __name__ == '__main__': parser = argparse.ArgumentParser() for param",
"if request_endpoints is not None: request_endpoints = [request_endpoints[i * 3:(i",
"line in tp: lines.append(line) lines.append(\"\\nif __name__ == '__main__':\") if params['wsgiserver']:",
"create_flask_app(app='flask_app', threading=False, wsgiserver=False, unwanted_warnings=False, logging=False, further_logging=False, site_endpoints=None, endpoints=None, request_endpoints=None): check_for_pkg('flask')",
"\"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import logging\", \"\", \"#Logging",
"in headers.keys(): if params[param]: for line in headers[param]: lines.append(line) lines.append(\"\\ndef",
"= [\"\\n@app.route('/endpoint')\", \"def endpoint():\", \"\\t#endpoint.html\", \"\\treturn endpoint_route\"] for line in",
"request_endpoints: print('Endpoint: ' + ep, '\\nMethod: ' + request_method, '\\nParameter:",
"server forever\") lines.append(\"\\tkeep_alive()\") else: lines.append(\"\\t#Run server\") lines.append(\"\\trun()\") for line in",
"+ ep, '\\nMethod: ' + request_method, '\\nParameter: ' + request_param)",
"request_method, ep, request_param in request_endpoints: print('Endpoint: ' + ep, '\\nMethod:",
"\"Endpoint\" \"Parameter\"') if param == 'app': if args[param] != None:",
"3:(i + 1) * 3] for i in range((len(request_endpoints) +",
"Flask(__name__)\", \"\", \"@app.route('/')\", \"def main():\", \"\\t#index.html\", \"\\treturn codecs.open('web/index.html', 'r', 'utf-8').read()\",",
"ep in endpoints: print('Endpoint: ' + ep) tp = [\"\\n@app.route('/endpoint')\",",
"\"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import logging\", \"\", \"#Logging configuration set",
"for line in [\"\", \"app = Flask(__name__)\", \"\", \"@app.route('/')\", \"def",
"'--'+param.lower(), nargs='+', help='', required=False) else: parser.add_argument('-'+param[0].lower(), '--'+param.lower(), help='', required=False) args",
"send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')\"]: lines.append(line) site_endpoints = params['site_endpoints'] if site_endpoints is",
"= open(project+'/'+project+\".py\",\"w+\") headers = { 'threading': [\"\", \"#Threading\", \"from threading",
"if param == 'app': if args[param] != None: params[param] =",
"[\"\", \"#Disable Warnings\", \"import warnings\", \"warnings.filterwarnings('ignore')\"], 'logging': [\"\", \"#Logging\", \"import",
"project + ' app succesfully.') for param in params.keys(): if",
"request_endpoints=None): check_for_pkg('flask') lines = [\"from flask import Flask, send_from_directory\",\"import codecs\",",
"\"#Threading\", \"from threading import Thread\"], 'wsgiserver': [\"\", \"#WSGIServer\", \"from gevent.pywsgi",
"lines.append(\"\\tapp.run(host='0.0.0.0',port=8081)\") if params['threading']: for line in [\"\", \"#Thread\", \"def keep_alive():\",",
"endpoints = params['endpoints'] if endpoints is not None: for ep",
"'__main__': parser = argparse.ArgumentParser() for param in params.keys(): if 'endpoints'"
] |
[
"set the database url in the environ db_url = os.environ.get(\"DATABASE_URL\")",
"folder db_url = \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the",
"Flask application.\"\"\" app = Flask(__name__, instance_relative_config=True) # some deploy systems",
"app.config.from_pyfile(\"config.py\", silent=True) else: # load the test config if passed",
"init_db_command(): \"\"\"Clear existing data and create new tables.\"\"\" init_db() click.echo(\"Initialized",
"the blueprints to the app from flaskr import auth, blog",
"db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear existing data and create",
"configure an instance of the Flask application.\"\"\" app = Flask(__name__,",
"app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\" point at \"/\", which is",
"SQLAlchemy __version__ = (1, 0, 0, \"dev\") db = SQLAlchemy()",
"in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if",
"by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app def init_db(): db.drop_all() db.create_all()",
"@with_appcontext def init_db_command(): \"\"\"Clear existing data and create new tables.\"\"\"",
"database in the instance folder db_url = \"sqlite:///\" + os.path.join(app.instance_path,",
"import with_appcontext from flask_sqlalchemy import SQLAlchemy __version__ = (1, 0,",
"should be overridden in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url,",
"def create_app(test_config=None): \"\"\"Create and configure an instance of the Flask",
"instance_relative_config=True) # some deploy systems set the database url in",
"the Flask application.\"\"\" app = Flask(__name__, instance_relative_config=True) # some deploy",
"SQLAlchemy() def create_app(test_config=None): \"\"\"Create and configure an instance of the",
"flask_sqlalchemy import SQLAlchemy __version__ = (1, 0, 0, \"dev\") db",
"app.register_blueprint(blog.bp) # make \"index\" point at \"/\", which is handled",
"None: # load the instance config, if it exists, when",
"default to a sqlite database in the instance folder db_url",
"the init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints to",
"some deploy systems set the database url in the environ",
"SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None: # load the instance",
"from flask_sqlalchemy import SQLAlchemy __version__ = (1, 0, 0, \"dev\")",
"systems set the database url in the environ db_url =",
"folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret that should",
"auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\" point at \"/\",",
"db_url = os.environ.get(\"DATABASE_URL\") if db_url is None: # default to",
"with_appcontext from flask_sqlalchemy import SQLAlchemy __version__ = (1, 0, 0,",
"silent=True) else: # load the test config if passed in",
"= SQLAlchemy() def create_app(test_config=None): \"\"\"Create and configure an instance of",
"and configure an instance of the Flask application.\"\"\" app =",
"make \"index\" point at \"/\", which is handled by \"blog.index\"",
"environ db_url = os.environ.get(\"DATABASE_URL\") if db_url is None: # default",
"= Flask(__name__, instance_relative_config=True) # some deploy systems set the database",
"\"/\", which is handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app",
"the database url in the environ db_url = os.environ.get(\"DATABASE_URL\") if",
"create_app(test_config=None): \"\"\"Create and configure an instance of the Flask application.\"\"\"",
"db_url = \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the instance",
"Flask(__name__, instance_relative_config=True) # some deploy systems set the database url",
"app = Flask(__name__, instance_relative_config=True) # some deploy systems set the",
"# load the test config if passed in app.config.update(test_config) #",
"existing data and create new tables.\"\"\" init_db() click.echo(\"Initialized the database.\")",
"and the init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints",
"= (1, 0, 0, \"dev\") db = SQLAlchemy() def create_app(test_config=None):",
"test_config is None: # load the instance config, if it",
"\"index\" point at \"/\", which is handled by \"blog.index\" app.add_url_rule(\"/\",",
"handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app def init_db(): db.drop_all()",
"# default secret that should be overridden in environ or",
"def init_db_command(): \"\"\"Clear existing data and create new tables.\"\"\" init_db()",
"flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\" point",
"# load the instance config, if it exists, when not",
"\"flaskr.sqlite\") # ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping(",
"app.config.from_mapping( # default secret that should be overridden in environ",
"a sqlite database in the instance folder db_url = \"sqlite:///\"",
"in the instance folder db_url = \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\")",
"# make \"index\" point at \"/\", which is handled by",
"(1, 0, 0, \"dev\") db = SQLAlchemy() def create_app(test_config=None): \"\"\"Create",
"secret that should be overridden in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\",",
") if test_config is None: # load the instance config,",
"import os import click from flask import Flask from flask.cli",
"command db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints to the app",
"load the instance config, if it exists, when not testing",
"else: # load the test config if passed in app.config.update(test_config)",
"app.config.update(test_config) # initialize Flask-SQLAlchemy and the init-db command db.init_app(app) app.cli.add_command(init_db_command)",
"init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints to the",
"exist_ok=True) app.config.from_mapping( # default secret that should be overridden in",
"Flask from flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy __version__",
"that should be overridden in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"),",
"<filename>examples/flaskr/flaskr/__init__.py import os import click from flask import Flask from",
"config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None:",
"passed in app.config.update(test_config) # initialize Flask-SQLAlchemy and the init-db command",
"url in the environ db_url = os.environ.get(\"DATABASE_URL\") if db_url is",
"\"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the instance folder exists",
"is handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app def init_db():",
"init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear existing data",
"instance folder db_url = \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure",
"os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret that should be overridden",
"db = SQLAlchemy() def create_app(test_config=None): \"\"\"Create and configure an instance",
"# apply the blueprints to the app from flaskr import",
"the instance config, if it exists, when not testing app.config.from_pyfile(\"config.py\",",
"test config if passed in app.config.update(test_config) # initialize Flask-SQLAlchemy and",
"default secret that should be overridden in environ or config",
"be overridden in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False,",
"\"\"\"Clear existing data and create new tables.\"\"\" init_db() click.echo(\"Initialized the",
"the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret",
"sqlite database in the instance folder db_url = \"sqlite:///\" +",
"environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config",
"in app.config.update(test_config) # initialize Flask-SQLAlchemy and the init-db command db.init_app(app)",
"the test config if passed in app.config.update(test_config) # initialize Flask-SQLAlchemy",
"import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\" point at",
"apply the blueprints to the app from flaskr import auth,",
"in the environ db_url = os.environ.get(\"DATABASE_URL\") if db_url is None:",
"overridden in environ or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, )",
"if test_config is None: # load the instance config, if",
"SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None: #",
"application.\"\"\" app = Flask(__name__, instance_relative_config=True) # some deploy systems set",
"exists, when not testing app.config.from_pyfile(\"config.py\", silent=True) else: # load the",
"import SQLAlchemy __version__ = (1, 0, 0, \"dev\") db =",
"to the app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp)",
"testing app.config.from_pyfile(\"config.py\", silent=True) else: # load the test config if",
"= os.environ.get(\"DATABASE_URL\") if db_url is None: # default to a",
"db_url is None: # default to a sqlite database in",
"from flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy __version__ =",
"instance of the Flask application.\"\"\" app = Flask(__name__, instance_relative_config=True) #",
"= \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the instance folder",
"at \"/\", which is handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return",
"which is handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app def",
"is None: # load the instance config, if it exists,",
"# some deploy systems set the database url in the",
"0, 0, \"dev\") db = SQLAlchemy() def create_app(test_config=None): \"\"\"Create and",
"None: # default to a sqlite database in the instance",
"# default to a sqlite database in the instance folder",
"app.cli.add_command(init_db_command) # apply the blueprints to the app from flaskr",
"\"\"\"Create and configure an instance of the Flask application.\"\"\" app",
"ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default",
"when not testing app.config.from_pyfile(\"config.py\", silent=True) else: # load the test",
"instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret that",
"if passed in app.config.update(test_config) # initialize Flask-SQLAlchemy and the init-db",
"os import click from flask import Flask from flask.cli import",
"# initialize Flask-SQLAlchemy and the init-db command db.init_app(app) app.cli.add_command(init_db_command) #",
"not testing app.config.from_pyfile(\"config.py\", silent=True) else: # load the test config",
"the app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) #",
"__version__ = (1, 0, 0, \"dev\") db = SQLAlchemy() def",
"flask import Flask from flask.cli import with_appcontext from flask_sqlalchemy import",
"deploy systems set the database url in the environ db_url",
"the instance folder db_url = \"sqlite:///\" + os.path.join(app.instance_path, \"flaskr.sqlite\") #",
"# ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( #",
"flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy __version__ = (1,",
"instance config, if it exists, when not testing app.config.from_pyfile(\"config.py\", silent=True)",
"initialize Flask-SQLAlchemy and the init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply",
"@click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear existing data and create new",
"the environ db_url = os.environ.get(\"DATABASE_URL\") if db_url is None: #",
"db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear existing data and",
"+ os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the instance folder exists os.makedirs(app.instance_path,",
"endpoint=\"index\") return app def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def",
"SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None: # load the",
"import Flask from flask.cli import with_appcontext from flask_sqlalchemy import SQLAlchemy",
"from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\"",
"if it exists, when not testing app.config.from_pyfile(\"config.py\", silent=True) else: #",
"app def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear",
"app.add_url_rule(\"/\", endpoint=\"index\") return app def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext",
"if db_url is None: # default to a sqlite database",
"load the test config if passed in app.config.update(test_config) # initialize",
"or config SECRET_KEY=os.environ.get(\"SECRET_KEY\", \"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is",
"an instance of the Flask application.\"\"\" app = Flask(__name__, instance_relative_config=True)",
"0, \"dev\") db = SQLAlchemy() def create_app(test_config=None): \"\"\"Create and configure",
"database url in the environ db_url = os.environ.get(\"DATABASE_URL\") if db_url",
"is None: # default to a sqlite database in the",
"config if passed in app.config.update(test_config) # initialize Flask-SQLAlchemy and the",
"\"dev\") db = SQLAlchemy() def create_app(test_config=None): \"\"\"Create and configure an",
"of the Flask application.\"\"\" app = Flask(__name__, instance_relative_config=True) # some",
"app from flaskr import auth, blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make",
"point at \"/\", which is handled by \"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\")",
"config, if it exists, when not testing app.config.from_pyfile(\"config.py\", silent=True) else:",
"blog app.register_blueprint(auth.bp) app.register_blueprint(blog.bp) # make \"index\" point at \"/\", which",
"Flask-SQLAlchemy and the init-db command db.init_app(app) app.cli.add_command(init_db_command) # apply the",
"\"dev\"), SQLALCHEMY_DATABASE_URI=db_url, SQLALCHEMY_TRACK_MODIFICATIONS=False, ) if test_config is None: # load",
"return app def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command():",
"from flask import Flask from flask.cli import with_appcontext from flask_sqlalchemy",
"exists os.makedirs(app.instance_path, exist_ok=True) app.config.from_mapping( # default secret that should be",
"click from flask import Flask from flask.cli import with_appcontext from",
"it exists, when not testing app.config.from_pyfile(\"config.py\", silent=True) else: # load",
"import click from flask import Flask from flask.cli import with_appcontext",
"blueprints to the app from flaskr import auth, blog app.register_blueprint(auth.bp)",
"def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\") @with_appcontext def init_db_command(): \"\"\"Clear existing",
"\"blog.index\" app.add_url_rule(\"/\", endpoint=\"index\") return app def init_db(): db.drop_all() db.create_all() @click.command(\"init-db\")",
"os.path.join(app.instance_path, \"flaskr.sqlite\") # ensure the instance folder exists os.makedirs(app.instance_path, exist_ok=True)",
"to a sqlite database in the instance folder db_url =",
"os.environ.get(\"DATABASE_URL\") if db_url is None: # default to a sqlite",
"db.init_app(app) app.cli.add_command(init_db_command) # apply the blueprints to the app from"
] |
[
"<gh_stars>1-10 import os, sys fn = sys.argv[1] if os.system('python compile.py",
"= sys.argv[1] if os.system('python compile.py %s __tmp.S' % fn) ==",
"% fn) == 0: os.system('python asm.py __tmp.S %s' % fn[:-2])",
"fn = sys.argv[1] if os.system('python compile.py %s __tmp.S' % fn)",
"sys fn = sys.argv[1] if os.system('python compile.py %s __tmp.S' %",
"import os, sys fn = sys.argv[1] if os.system('python compile.py %s",
"if os.system('python compile.py %s __tmp.S' % fn) == 0: os.system('python",
"compile.py %s __tmp.S' % fn) == 0: os.system('python asm.py __tmp.S",
"%s __tmp.S' % fn) == 0: os.system('python asm.py __tmp.S %s'",
"__tmp.S' % fn) == 0: os.system('python asm.py __tmp.S %s' %",
"os.system('python compile.py %s __tmp.S' % fn) == 0: os.system('python asm.py",
"sys.argv[1] if os.system('python compile.py %s __tmp.S' % fn) == 0:",
"os, sys fn = sys.argv[1] if os.system('python compile.py %s __tmp.S'"
] |
[
"# # @param world Reference to the World object this",
"# @package Actor # @author <NAME> # @date 26/08/2020 #",
"the actor with ID 1 shows the following result on",
"of the first Actor object is 0. # - The",
"# @author <NAME> # @date 26/08/2020 # # Actor class,",
"Sets the unique ID for the object and initializes the",
"ID of the first Actor object is 0. # -",
"getID(self): return self.__actorID ## # Used for testing # @return",
"else: raise ValueError ## # Sets the world this actor",
"into. # # @return the x coordinate of this Actor",
"RuntimeError when the world is null. # def setLocation(self, x,",
"when x < 0 or x >= world width, #",
"the X coordinate of the cell this actor object is",
"member variables. # - Sets the unique ID for the",
"zero and initialize the location of the # object to",
"@package Actor # @author <NAME> # @date 26/08/2020 # #",
"class, which is the base class for Disease objects. #",
"@return the world this object belongs to # def getWorld(self):",
"# Gets the X coordinate of the cell this actor",
"Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ## # Sets the",
"st += 'position = (%d, %d)\\n' % (self.getX(), self.getY()) return",
"ID>@f$ is # replaced by the unique ID of the",
"base class for Disease objects. # ## class Actor: #",
"ID of the Actor object that performs the act(self) #",
"## # Gets the X coordinate of the cell this",
"# def getWorld(self): return self.__world ## # Gets the X",
"Actor object. # def getY(self): return self.__locY ## # Return",
"Reference to the World object this Actor object is added.",
"null. # def setLocation(self, x, y): if self.__world is None:",
"# Iteration counter. self.__itCounter = 0 ## # Used for",
"new Actor object. # - Sets the initial values of",
"# # For instance, the actor with ID 1 shows",
"incremented by one each time a new Actor object is",
"is 0. # - The ID gets incremented by one",
"# Sets the cell coordinates of this object. # #",
"# object to which this Actor object belongs to null.",
"act(self) method has been called twice. # <PRE> # Iteration",
"is null. # def setLocation(self, x, y): if self.__world is",
"self.__world ## # Gets the X coordinate of the cell",
"Actor object is added. # @throws RuntimeError when world is",
"UTF-8 # # @package Actor # @author <NAME> # @date",
"testing # @return number of iterations # def Iteration(self): return",
"y >= world height, # @throws RuntimeError when the world",
"the # object to cell (0,0). # def __init__(self): #",
"of this object. # # @param x the column. #",
"when world is null. # def addedToWorld(self, world): if world",
"= 0 # World this actor belongs to. self.__world =",
"the initial values of its member variables. # - Sets",
">= world height, # @throws RuntimeError when the world is",
"world width, # @throws ValueError when y < 0 or",
"to zero and initialize the location of the # object",
"0 or y >= world height, # @throws RuntimeError when",
"Actor class, which is the base class for Disease objects.",
"the base class for Disease objects. # ## class Actor:",
"initializes the reference to the World # object to which",
"to the World object this Actor object is added. #",
"the value of the next \"free\" id. __ID = 0",
"the first Actor object is 0. # - The ID",
"actor. self.__locX = 0 # Y coordinate of this actor.",
"addedToWorld(self, world): if world is None: raise RuntimeError self.__world =",
"this actor object is into. # # @return the y",
"is into. # # @return the y coordinate of this",
"Gets the X coordinate of the cell this actor object",
"with ID 1 shows the following result on # the",
"return self.__itCounter ## # Prints on screen in the format",
"@throws RuntimeError when the world is null. # def setLocation(self,",
"is None: raise RuntimeError if (0 <= x < self.__world.getWidth())",
"method has been called twice. # <PRE> # Iteration 0:",
"# The @f$<ID>@f$ is replaced by the current iteration number.",
"self.__world.getHeight()): self.__locX = x self.__locY = y else: raise ValueError",
"coordinate of this actor. self.__locX = 0 # Y coordinate",
"= world ## # Gets the world this object in",
"# method. # # For instance, the actor with ID",
"<NAME> # @date 26/08/2020 # # Actor class, which is",
"in the format \"Iteration <ID>: Actor <Actor ID>\". # #",
"%d)\\n' % (self.getX(), self.getY()) except TypeError: st = \"ID =",
"## # Prints on screen in the format \"Iteration <ID>:",
"# X coordinate of this actor. self.__locX = 0 #",
"<= x < self.__world.getWidth()) and (0 <= y < self.__world.getHeight()):",
"0: Actor 1 # Iteration 1: Actor 1 # </PRE>",
"when the world is null. # def setLocation(self, x, y):",
"into. # # @return the world this object belongs to",
"values of its member variables. # - Sets the unique",
"+= 'position = (%d, %d)\\n' % (self.getX(), self.getY()) return st",
"y the row. # # @throws ValueError when x <",
"object belongs to null. # - The ID of the",
"raise RuntimeError self.__world = world ## # Gets the world",
"X coordinate of this actor. self.__locX = 0 # Y",
"following result on # the output screen after its act(self)",
"x >= world width, # @throws ValueError when y <",
"actor ID and position. # def __str__(self): try: st =",
"Iteration 1: Actor 1 # </PRE> # def act(self): print(\"Iteration",
"object. # def getY(self): return self.__locY ## # Return a",
"y coordinate of this Actor object. # def getY(self): return",
"ValueError ## # Sets the world this actor is into.",
"= (%d, %d)\\n' % (self.getX(), self.getY()) except TypeError: st =",
"{}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ## # Sets the cell",
"the current iteration number. @f$<Actor ID>@f$ is # replaced by",
"this object in into. # # @return the world this",
"instance, the actor with ID 1 shows the following result",
"string with this actor ID and position. # def __str__(self):",
"- Sets the initial values of its member variables. #",
"this Actor object. # def getX(self): return self.__locX ## #",
"cell this actor object is into. # # @return the",
"this actor. self.__locY = 0 # World this actor belongs",
"# @param world Reference to the World object this Actor",
"'.encode('utf-8') % self.getID() st += 'position = (%d, %d)\\n' %",
"width, # @throws ValueError when y < 0 or y",
"(0 <= x < self.__world.getWidth()) and (0 <= y <",
"@throws RuntimeError when world is null. # def addedToWorld(self, world):",
"if self.__world is None: raise RuntimeError if (0 <= x",
"first Actor object is 0. # - The ID gets",
"Holds the value of the next \"free\" id. __ID =",
"this actor object is into. # # @return the x",
"self.__world.getWidth()) and (0 <= y < self.__world.getHeight()): self.__locX = x",
"# # Actor class, which is the base class for",
"method. # # For instance, the actor with ID 1",
"x coordinate of this Actor object. # def getX(self): return",
"the row. # # @throws ValueError when x < 0",
"world height, # @throws RuntimeError when the world is null.",
"belongs to null. # - The ID of the first",
"Actor.__ID += 1 # Iteration counter. self.__itCounter = 0 ##",
"iteration number. @f$<Actor ID>@f$ is # replaced by the unique",
"# # @param x the column. # @param y the",
"to which this Actor object belongs to null. # -",
"act(self) # method. # # For instance, the actor with",
"twice. # <PRE> # Iteration 0: Actor 1 # Iteration",
"or y >= world height, # @throws RuntimeError when the",
"of this Actor object. # def getX(self): return self.__locX ##",
"return self.__world ## # Gets the X coordinate of the",
"# @throws RuntimeError when the world is null. # def",
"the World object this Actor object is added. # @throws",
"counter to zero and initialize the location of the #",
"y < 0 or y >= world height, # @throws",
"iterations # def Iteration(self): return self.__itCounter ## # Prints on",
"def Iteration(self): return self.__itCounter ## # Prints on screen in",
"value of the next \"free\" id. __ID = 0 ##",
"belongs to # def getWorld(self): return self.__world ## # Gets",
"replaced by the unique ID of the Actor object that",
"performs the act(self) # method. # # For instance, the",
"Used for testing # @return number of iterations # def",
"next \"free\" id. __ID = 0 ## # Construct a",
"1 # Iteration counter. self.__itCounter = 0 ## # Used",
"to the World # object to which this Actor object",
"world this object belongs to # def getWorld(self): return self.__world",
"st = \"ID = %d \"u'\\u2192 '.encode('utf-8') % self.getID() st",
"the cell coordinates of this object. # # @param x",
"# def getY(self): return self.__locY ## # Return a string",
"# World this actor belongs to. self.__world = None #",
"- The ID of the first Actor object is 0.",
"is into. # # @return the x coordinate of this",
"\"free\" id. __ID = 0 ## # Construct a new",
"is None: raise RuntimeError self.__world = world ## # Gets",
"# </PRE> # def act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID))",
"self.__itCounter += 1 ## # Sets the cell coordinates of",
"y): if self.__world is None: raise RuntimeError if (0 <=",
"object to cell (0,0). # def __init__(self): # X coordinate",
"Actor object. # - Sets the initial values of its",
"Actor object that performs the act(self) # method. # #",
"row. # # @throws ValueError when x < 0 or",
"objects. # ## class Actor: # Holds the value of",
"id. __ID = 0 ## # Construct a new Actor",
"# @param y the row. # # @throws ValueError when",
"1 # Iteration 1: Actor 1 # </PRE> # def",
"return self.__locX ## # Gets the Y coordinate of the",
"= %d \"u'\\u2192 ' % self.getID() st += 'position =",
"Construct a new Actor object. # - Sets the initial",
"this actor. self.__locX = 0 # Y coordinate of this",
"= \"ID = %d \"u'\\u2192 '.encode('utf-8') % self.getID() st +=",
"@throws ValueError when x < 0 or x >= world",
"variables. # - Sets the unique ID for the object",
"x < 0 or x >= world width, # @throws",
"# Construct a new Actor object. # - Sets the",
"testing # @return ActorID # def getID(self): return self.__actorID ##",
"world Reference to the World object this Actor object is",
"of its member variables. # - Sets the unique ID",
"iteration counter to zero and initialize the location of the",
"= Actor.__ID Actor.__ID += 1 # Iteration counter. self.__itCounter =",
"RuntimeError if (0 <= x < self.__world.getWidth()) and (0 <=",
"def act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1",
"__str__(self): try: st = \"ID = %d \"u'\\u2192 '.encode('utf-8') %",
"one each time a new Actor object is created. #",
"self.__actorID)) self.__itCounter += 1 ## # Sets the cell coordinates",
"## # Gets the Y coordinate of the cell this",
"+= 1 # Iteration counter. self.__itCounter = 0 ## #",
"st += 'position = (%d, %d)\\n' % (self.getX(), self.getY()) except",
"def __str__(self): try: st = \"ID = %d \"u'\\u2192 '.encode('utf-8')",
"# Gets the world this object in into. # #",
"% (self.getX(), self.getY()) except TypeError: st = \"ID = %d",
"initial values of its member variables. # - Sets the",
"after its act(self) method has been called twice. # <PRE>",
"this actor ID and position. # def __str__(self): try: st",
"is null. # def addedToWorld(self, world): if world is None:",
"# - Sets the unique ID for the object and",
"# Sets the world this actor is into. # #",
"{}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ## # Sets",
"unique ID of the Actor object that performs the act(self)",
"# Iteration 0: Actor 1 # Iteration 1: Actor 1",
"self.__locY = y else: raise ValueError ## # Sets the",
"Gets the Y coordinate of the cell this actor object",
"Actor 1 # </PRE> # def act(self): print(\"Iteration {}: Actor",
"<= y < self.__world.getHeight()): self.__locX = x self.__locY = y",
"act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ##",
"and position. # def __str__(self): try: st = \"ID =",
"@return number of iterations # def Iteration(self): return self.__itCounter ##",
"column. # @param y the row. # # @throws ValueError",
"def setLocation(self, x, y): if self.__world is None: raise RuntimeError",
"# @return the world this object belongs to # def",
"<reponame>ariadnepinheiro/Disease_Simulator #!/usr/bin/env python # coding: UTF-8 # # @package Actor",
"its member variables. # - Sets the unique ID for",
"this Actor object belongs to null. # - The ID",
"## # Sets the cell coordinates of this object. #",
"@f$<Actor ID>@f$ is # replaced by the unique ID of",
"cell (0,0). # def __init__(self): # X coordinate of this",
"# Return a string with this actor ID and position.",
"\"u'\\u2192 '.encode('utf-8') % self.getID() st += 'position = (%d, %d)\\n'",
"%d \"u'\\u2192 ' % self.getID() st += 'position = (%d,",
"by the current iteration number. @f$<Actor ID>@f$ is # replaced",
"## # Gets the world this object in into. #",
"and initializes the reference to the World # object to",
"to cell (0,0). # def __init__(self): # X coordinate of",
"## # Sets the world this actor is into. #",
"World object this Actor object is added. # @throws RuntimeError",
"the world this object belongs to # def getWorld(self): return",
"# def act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter +=",
"= %d \"u'\\u2192 '.encode('utf-8') % self.getID() st += 'position =",
"The ID of the first Actor object is 0. #",
"def getX(self): return self.__locX ## # Gets the Y coordinate",
"world this object in into. # # @return the world",
"X coordinate of the cell this actor object is into.",
"coordinate of this Actor object. # def getY(self): return self.__locY",
"## # Used for testing # @return ActorID # def",
"raise ValueError ## # Sets the world this actor is",
"# <PRE> # Iteration 0: Actor 1 # Iteration 1:",
"null. # - The ID of the first Actor object",
"# Prints on screen in the format \"Iteration <ID>: Actor",
"the x coordinate of this Actor object. # def getX(self):",
"## class Actor: # Holds the value of the next",
"screen after its act(self) method has been called twice. #",
"# def setLocation(self, x, y): if self.__world is None: raise",
"actor object is into. # # @return the y coordinate",
"self.__locX = 0 # Y coordinate of this actor. self.__locY",
"is the base class for Disease objects. # ## class",
"object is 0. # - The ID gets incremented by",
"@date 26/08/2020 # # Actor class, which is the base",
"Actor object is created. # - Sets the iteration counter",
"Gets the world this object in into. # # @return",
"Actor object. # def getX(self): return self.__locX ## # Gets",
"\"ID = %d \"u'\\u2192 ' % self.getID() st += 'position",
"python # coding: UTF-8 # # @package Actor # @author",
"world): if world is None: raise RuntimeError self.__world = world",
"cell coordinates of this object. # # @param x the",
"when y < 0 or y >= world height, #",
"<Actor ID>\". # # The @f$<ID>@f$ is replaced by the",
"1 shows the following result on # the output screen",
"1: Actor 1 # </PRE> # def act(self): print(\"Iteration {}:",
"ValueError when x < 0 or x >= world width,",
"Actor object belongs to null. # - The ID of",
"@throws ValueError when y < 0 or y >= world",
"and (0 <= y < self.__world.getHeight()): self.__locX = x self.__locY",
"%d \"u'\\u2192 '.encode('utf-8') % self.getID() st += 'position = (%d,",
"0 ## # Used for testing # @return ActorID #",
"0 or x >= world width, # @throws ValueError when",
"height, # @throws RuntimeError when the world is null. #",
"def getID(self): return self.__actorID ## # Used for testing #",
"class Actor: # Holds the value of the next \"free\"",
"Y coordinate of the cell this actor object is into.",
"self.__itCounter = 0 ## # Used for testing # @return",
"# def __str__(self): try: st = \"ID = %d \"u'\\u2192",
"this actor is into. # # @param world Reference to",
"of this actor. self.__locY = 0 # World this actor",
"# def addedToWorld(self, world): if world is None: raise RuntimeError",
"position. # def __str__(self): try: st = \"ID = %d",
"a new Actor object is created. # - Sets the",
"< 0 or x >= world width, # @throws ValueError",
"world is null. # def setLocation(self, x, y): if self.__world",
"location of the # object to cell (0,0). # def",
"to. self.__world = None # Unique identifier for this actor.",
"of the cell this actor object is into. # #",
"= 0 # Y coordinate of this actor. self.__locY =",
"1 ## # Sets the cell coordinates of this object.",
"is replaced by the current iteration number. @f$<Actor ID>@f$ is",
"ID gets incremented by one each time a new Actor",
"to null. # - The ID of the first Actor",
"the following result on # the output screen after its",
"actor belongs to. self.__world = None # Unique identifier for",
"Iteration(self): return self.__itCounter ## # Prints on screen in the",
"# Used for testing # @return number of iterations #",
"@f$<ID>@f$ is replaced by the current iteration number. @f$<Actor ID>@f$",
"world is null. # def addedToWorld(self, world): if world is",
"# # @throws ValueError when x < 0 or x",
"Actor # @author <NAME> # @date 26/08/2020 # # Actor",
"raise RuntimeError if (0 <= x < self.__world.getWidth()) and (0",
"of the Actor object that performs the act(self) # method.",
"1 # </PRE> # def act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter,",
"the iteration counter to zero and initialize the location of",
"which this Actor object belongs to null. # - The",
"in into. # # @return the world this object belongs",
"time a new Actor object is created. # - Sets",
"# Actor class, which is the base class for Disease",
"actor. self.__actorID = Actor.__ID Actor.__ID += 1 # Iteration counter.",
"26/08/2020 # # Actor class, which is the base class",
"Sets the iteration counter to zero and initialize the location",
"by the unique ID of the Actor object that performs",
"with this actor ID and position. # def __str__(self): try:",
"@author <NAME> # @date 26/08/2020 # # Actor class, which",
"def getWorld(self): return self.__world ## # Gets the X coordinate",
"\"u'\\u2192 ' % self.getID() st += 'position = (%d, %d)\\n'",
"a string with this actor ID and position. # def",
"# - The ID gets incremented by one each time",
"try: st = \"ID = %d \"u'\\u2192 '.encode('utf-8') % self.getID()",
"for this actor. self.__actorID = Actor.__ID Actor.__ID += 1 #",
"object. # # @param x the column. # @param y",
"__ID = 0 ## # Construct a new Actor object.",
"if world is None: raise RuntimeError self.__world = world ##",
"Iteration counter. self.__itCounter = 0 ## # Used for testing",
"for testing # @return number of iterations # def Iteration(self):",
"the column. # @param y the row. # # @throws",
"</PRE> # def act(self): print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter",
"## # Construct a new Actor object. # - Sets",
"self.__world is None: raise RuntimeError if (0 <= x <",
"# @param x the column. # @param y the row.",
"# Holds the value of the next \"free\" id. __ID",
"# Y coordinate of this actor. self.__locY = 0 #",
"the Actor object that performs the act(self) # method. #",
"coordinate of the cell this actor object is into. #",
"of iterations # def Iteration(self): return self.__itCounter ## # Prints",
"def __init__(self): # X coordinate of this actor. self.__locX =",
"Actor 1 # Iteration 1: Actor 1 # </PRE> #",
"Sets the initial values of its member variables. # -",
"that performs the act(self) # method. # # For instance,",
"new Actor object is created. # - Sets the iteration",
"self.__locX ## # Gets the Y coordinate of the cell",
"<ID>: Actor <Actor ID>\". # # The @f$<ID>@f$ is replaced",
"by one each time a new Actor object is created.",
"ID 1 shows the following result on # the output",
"Sets the world this actor is into. # # @param",
"the unique ID for the object and initializes the reference",
"counter. self.__itCounter = 0 ## # Used for testing #",
"# - The ID of the first Actor object is",
"output screen after its act(self) method has been called twice.",
"y < self.__world.getHeight()): self.__locX = x self.__locY = y else:",
"0 # World this actor belongs to. self.__world = None",
"coordinate of this Actor object. # def getX(self): return self.__locX",
"ID and position. # def __str__(self): try: st = \"ID",
"= 0 ## # Used for testing # @return ActorID",
"which is the base class for Disease objects. # ##",
"@return the x coordinate of this Actor object. # def",
"coding: UTF-8 # # @package Actor # @author <NAME> #",
"None: raise RuntimeError if (0 <= x < self.__world.getWidth()) and",
"on screen in the format \"Iteration <ID>: Actor <Actor ID>\".",
"The @f$<ID>@f$ is replaced by the current iteration number. @f$<Actor",
"RuntimeError self.__world = world ## # Gets the world this",
"Return a string with this actor ID and position. #",
"# # @return the y coordinate of this Actor object.",
"x, y): if self.__world is None: raise RuntimeError if (0",
"object is created. # - Sets the iteration counter to",
"# def Iteration(self): return self.__itCounter ## # Prints on screen",
"0. # - The ID gets incremented by one each",
"@param y the row. # # @throws ValueError when x",
"belongs to. self.__world = None # Unique identifier for this",
"# @throws RuntimeError when world is null. # def addedToWorld(self,",
"this actor. self.__actorID = Actor.__ID Actor.__ID += 1 # Iteration",
"Disease objects. # ## class Actor: # Holds the value",
"the reference to the World # object to which this",
"Used for testing # @return ActorID # def getID(self): return",
"(self.getX(), self.getY()) except TypeError: st = \"ID = %d \"u'\\u2192",
"format \"Iteration <ID>: Actor <Actor ID>\". # # The @f$<ID>@f$",
"of this actor. self.__locX = 0 # Y coordinate of",
"number of iterations # def Iteration(self): return self.__itCounter ## #",
"return self.__locY ## # Return a string with this actor",
"self.getID() st += 'position = (%d, %d)\\n' % (self.getX(), self.getY())",
"a new Actor object. # - Sets the initial values",
"- Sets the unique ID for the object and initializes",
"# object to cell (0,0). # def __init__(self): # X",
"- The ID gets incremented by one each time a",
"def addedToWorld(self, world): if world is None: raise RuntimeError self.__world",
"# Used for testing # @return ActorID # def getID(self):",
"of the next \"free\" id. __ID = 0 ## #",
"object is into. # # @return the y coordinate of",
"Iteration 0: Actor 1 # Iteration 1: Actor 1 #",
"Actor object is 0. # - The ID gets incremented",
"# ## class Actor: # Holds the value of the",
"# @return number of iterations # def Iteration(self): return self.__itCounter",
"the Y coordinate of the cell this actor object is",
"ID>\". # # The @f$<ID>@f$ is replaced by the current",
"World this actor belongs to. self.__world = None # Unique",
"this Actor object. # def getY(self): return self.__locY ## #",
"the cell this actor object is into. # # @return",
">= world width, # @throws ValueError when y < 0",
"self.__locY ## # Return a string with this actor ID",
"self.__world = world ## # Gets the world this object",
"# Gets the Y coordinate of the cell this actor",
"## # Used for testing # @return number of iterations",
"for Disease objects. # ## class Actor: # Holds the",
"this actor belongs to. self.__world = None # Unique identifier",
"= 0 ## # Construct a new Actor object. #",
"actor is into. # # @param world Reference to the",
"' % self.getID() st += 'position = (%d, %d)\\n' %",
"< self.__world.getHeight()): self.__locX = x self.__locY = y else: raise",
"been called twice. # <PRE> # Iteration 0: Actor 1",
"Unique identifier for this actor. self.__actorID = Actor.__ID Actor.__ID +=",
"< self.__world.getWidth()) and (0 <= y < self.__world.getHeight()): self.__locX =",
"# def getID(self): return self.__actorID ## # Used for testing",
"object that performs the act(self) # method. # # For",
"- Sets the iteration counter to zero and initialize the",
"0 # Y coordinate of this actor. self.__locY = 0",
"RuntimeError when world is null. # def addedToWorld(self, world): if",
"world ## # Gets the world this object in into.",
"the world this object in into. # # @return the",
"# Iteration 1: Actor 1 # </PRE> # def act(self):",
"the location of the # object to cell (0,0). #",
"actor. self.__locY = 0 # World this actor belongs to.",
"Actor <Actor ID>\". # # The @f$<ID>@f$ is replaced by",
"ID for the object and initializes the reference to the",
"y else: raise ValueError ## # Sets the world this",
"# For instance, the actor with ID 1 shows the",
"x the column. # @param y the row. # #",
"unique ID for the object and initializes the reference to",
"def getY(self): return self.__locY ## # Return a string with",
"= None # Unique identifier for this actor. self.__actorID =",
"object is added. # @throws RuntimeError when world is null.",
"% self.getID() st += 'position = (%d, %d)\\n' % (self.getX(),",
"# @return the x coordinate of this Actor object. #",
"(%d, %d)\\n' % (self.getX(), self.getY()) except TypeError: st = \"ID",
"the world this actor is into. # # @param world",
"@param world Reference to the World object this Actor object",
"shows the following result on # the output screen after",
"or x >= world width, # @throws ValueError when y",
"to # def getWorld(self): return self.__world ## # Gets the",
"# @return the y coordinate of this Actor object. #",
"each time a new Actor object is created. # -",
"coordinates of this object. # # @param x the column.",
"class for Disease objects. # ## class Actor: # Holds",
"the World # object to which this Actor object belongs",
"coordinate of this actor. self.__locY = 0 # World this",
"# Unique identifier for this actor. self.__actorID = Actor.__ID Actor.__ID",
"= \"ID = %d \"u'\\u2192 ' % self.getID() st +=",
"None: raise RuntimeError self.__world = world ## # Gets the",
"self.__actorID ## # Used for testing # @return number of",
"# @return ActorID # def getID(self): return self.__actorID ## #",
"st = \"ID = %d \"u'\\u2192 ' % self.getID() st",
"self.__world = None # Unique identifier for this actor. self.__actorID",
"TypeError: st = \"ID = %d \"u'\\u2192 ' % self.getID()",
"the object and initializes the reference to the World #",
"# # @return the world this object belongs to #",
"ValueError when y < 0 or y >= world height,",
"= y else: raise ValueError ## # Sets the world",
"self.__locY = 0 # World this actor belongs to. self.__world",
"@param x the column. # @param y the row. #",
"ActorID # def getID(self): return self.__actorID ## # Used for",
"object to which this Actor object belongs to null. #",
"is added. # @throws RuntimeError when world is null. #",
"called twice. # <PRE> # Iteration 0: Actor 1 #",
"into. # # @return the y coordinate of this Actor",
"this object. # # @param x the column. # @param",
"object this Actor object is added. # @throws RuntimeError when",
"# - Sets the iteration counter to zero and initialize",
"# @throws ValueError when y < 0 or y >=",
"the act(self) # method. # # For instance, the actor",
"initialize the location of the # object to cell (0,0).",
"object in into. # # @return the world this object",
"this object belongs to # def getWorld(self): return self.__world ##",
"and initialize the location of the # object to cell",
"except TypeError: st = \"ID = %d \"u'\\u2192 ' %",
"self.__itCounter ## # Prints on screen in the format \"Iteration",
"getX(self): return self.__locX ## # Gets the Y coordinate of",
"x self.__locY = y else: raise ValueError ## # Sets",
"__init__(self): # X coordinate of this actor. self.__locX = 0",
"#!/usr/bin/env python # coding: UTF-8 # # @package Actor #",
"the next \"free\" id. __ID = 0 ## # Construct",
"reference to the World # object to which this Actor",
"of the # object to cell (0,0). # def __init__(self):",
"self.__actorID = Actor.__ID Actor.__ID += 1 # Iteration counter. self.__itCounter",
"World # object to which this Actor object belongs to",
"for testing # @return ActorID # def getID(self): return self.__actorID",
"actor with ID 1 shows the following result on #",
"into. # # @param world Reference to the World object",
"# @throws ValueError when x < 0 or x >=",
"Y coordinate of this actor. self.__locY = 0 # World",
"number. @f$<Actor ID>@f$ is # replaced by the unique ID",
"x < self.__world.getWidth()) and (0 <= y < self.__world.getHeight()): self.__locX",
"getWorld(self): return self.__world ## # Gets the X coordinate of",
"# # @return the x coordinate of this Actor object.",
"result on # the output screen after its act(self) method",
"# def getX(self): return self.__locX ## # Gets the Y",
"getY(self): return self.__locY ## # Return a string with this",
"for the object and initializes the reference to the World",
"created. # - Sets the iteration counter to zero and",
"# coding: UTF-8 # # @package Actor # @author <NAME>",
"object. # def getX(self): return self.__locX ## # Gets the",
"the unique ID of the Actor object that performs the",
"+= 'position = (%d, %d)\\n' % (self.getX(), self.getY()) except TypeError:",
"the format \"Iteration <ID>: Actor <Actor ID>\". # # The",
"\"Iteration <ID>: Actor <Actor ID>\". # # The @f$<ID>@f$ is",
"its act(self) method has been called twice. # <PRE> #",
"null. # def addedToWorld(self, world): if world is None: raise",
"# replaced by the unique ID of the Actor object",
"< 0 or y >= world height, # @throws RuntimeError",
"(0,0). # def __init__(self): # X coordinate of this actor.",
"replaced by the current iteration number. @f$<Actor ID>@f$ is #",
"# @date 26/08/2020 # # Actor class, which is the",
"self.getY()) except TypeError: st = \"ID = %d \"u'\\u2192 '",
"world this actor is into. # # @param world Reference",
"= x self.__locY = y else: raise ValueError ## #",
"print(\"Iteration {}: Actor {}\".format(self.__itCounter, self.__actorID)) self.__itCounter += 1 ## #",
"is created. # - Sets the iteration counter to zero",
"0 ## # Construct a new Actor object. # -",
"None # Unique identifier for this actor. self.__actorID = Actor.__ID",
"screen in the format \"Iteration <ID>: Actor <Actor ID>\". #",
"on # the output screen after its act(self) method has",
"Prints on screen in the format \"Iteration <ID>: Actor <Actor",
"the output screen after its act(self) method has been called",
"object belongs to # def getWorld(self): return self.__world ## #",
"object. # - Sets the initial values of its member",
"setLocation(self, x, y): if self.__world is None: raise RuntimeError if",
"is # replaced by the unique ID of the Actor",
"# - Sets the initial values of its member variables.",
"# # @package Actor # @author <NAME> # @date 26/08/2020",
"\"ID = %d \"u'\\u2192 '.encode('utf-8') % self.getID() st += 'position",
"current iteration number. @f$<Actor ID>@f$ is # replaced by the",
"this Actor object is added. # @throws RuntimeError when world",
"is into. # # @param world Reference to the World",
"Actor: # Holds the value of the next \"free\" id.",
"# def __init__(self): # X coordinate of this actor. self.__locX",
"the y coordinate of this Actor object. # def getY(self):",
"## # Return a string with this actor ID and",
"@return ActorID # def getID(self): return self.__actorID ## # Used",
"(0 <= y < self.__world.getHeight()): self.__locX = x self.__locY =",
"if (0 <= x < self.__world.getWidth()) and (0 <= y",
"object and initializes the reference to the World # object",
"# # The @f$<ID>@f$ is replaced by the current iteration",
"of this Actor object. # def getY(self): return self.__locY ##",
"# the output screen after its act(self) method has been",
"Sets the cell coordinates of this object. # # @param",
"actor object is into. # # @return the x coordinate",
"+= 1 ## # Sets the cell coordinates of this",
"object is into. # # @return the x coordinate of",
"self.__locX = x self.__locY = y else: raise ValueError ##",
"gets incremented by one each time a new Actor object",
"added. # @throws RuntimeError when world is null. # def",
"return self.__actorID ## # Used for testing # @return number",
"The ID gets incremented by one each time a new",
"<PRE> # Iteration 0: Actor 1 # Iteration 1: Actor",
"Actor.__ID Actor.__ID += 1 # Iteration counter. self.__itCounter = 0",
"For instance, the actor with ID 1 shows the following",
"world is None: raise RuntimeError self.__world = world ## #",
"@return the y coordinate of this Actor object. # def",
"'position = (%d, %d)\\n' % (self.getX(), self.getY()) except TypeError: st",
"identifier for this actor. self.__actorID = Actor.__ID Actor.__ID += 1",
"has been called twice. # <PRE> # Iteration 0: Actor",
"the world is null. # def setLocation(self, x, y): if"
] |
[
"binary.insert(0, num % 2) num >>= 1 if negative: return",
"int) -> str: \"\"\" Convert a Integer Decimal Number to",
"Convert a Integer Decimal Number to a Binary Number as",
"be interpreted as an integer \"\"\" if type(num) == float:",
"'float' object cannot be interpreted as an integer >>> #",
"def decimal_to_binary(num: int) -> str: \"\"\" Convert a Integer Decimal",
"interpreted as an integer >>> # strings will error as",
"= True num = -num binary = [] while num",
"\"0b0\" negative = False if num < 0: negative =",
"num = -num binary = [] while num > 0:",
"to a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>>",
"\"\".join(str(e) for e in binary) if __name__ == \"__main__\": import",
"if negative: return \"-0b\" + \"\".join(str(e) for e in binary)",
"a Integer Decimal Number to a Binary Number as str.",
"decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last): ...",
"type(num) == float: raise TypeError(\"'float' object cannot be interpreted as",
"decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> #",
"Number to a Binary Number as str. >>> decimal_to_binary(0) '0b0'",
">>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work",
"+ \"\".join(str(e) for e in binary) if __name__ == \"__main__\":",
"if num < 0: negative = True num = -num",
"True num = -num binary = [] while num >",
"\"\"\" if type(num) == float: raise TypeError(\"'float' object cannot be",
"\"-0b\" + \"\".join(str(e) for e in binary) return \"0b\" +",
"Binary Number.\"\"\" def decimal_to_binary(num: int) -> str: \"\"\" Convert a",
"last): ... TypeError: 'str' object cannot be interpreted as an",
"as an integer >>> # strings will error as well",
"type(num) == str: raise TypeError(\"'str' object cannot be interpreted as",
"be interpreted as an integer\") if type(num) == str: raise",
"interpreted as an integer \"\"\" if type(num) == float: raise",
"integer >>> # strings will error as well >>> decimal_to_binary('0xfffff')",
">>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>>",
"decimal_to_binary(-2) '-0b10' >>> # other floats will error >>> decimal_to_binary(16.16)",
">>> # strings will error as well >>> decimal_to_binary('0xfffff') #",
"num < 0: negative = True num = -num binary",
"while num > 0: binary.insert(0, num % 2) num >>=",
"-num binary = [] while num > 0: binary.insert(0, num",
"Integer Decimal Number to a Binary Number as str. >>>",
"2) num >>= 1 if negative: return \"-0b\" + \"\".join(str(e)",
"negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats",
"integer\") if num == 0: return \"0b0\" negative = False",
"negative = True num = -num binary = [] while",
"TypeError(\"'str' object cannot be interpreted as an integer\") if num",
"<reponame>smukk9/Python \"\"\"Convert a Decimal Number to a Binary Number.\"\"\" def",
"error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call",
"object cannot be interpreted as an integer >>> # strings",
"doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'str'",
"Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>>",
"== str: raise TypeError(\"'str' object cannot be interpreted as an",
"return \"0b0\" negative = False if num < 0: negative",
"str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111'",
"\"\".join(str(e) for e in binary) return \"0b\" + \"\".join(str(e) for",
"as an integer\") if type(num) == str: raise TypeError(\"'str' object",
"'0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>>",
"Number to a Binary Number.\"\"\" def decimal_to_binary(num: int) -> str:",
"\"\"\" Convert a Integer Decimal Number to a Binary Number",
"... TypeError: 'float' object cannot be interpreted as an integer",
"recent call last): ... TypeError: 'str' object cannot be interpreted",
">>= 1 if negative: return \"-0b\" + \"\".join(str(e) for e",
"call last): ... TypeError: 'str' object cannot be interpreted as",
"e in binary) if __name__ == \"__main__\": import doctest doctest.testmod()",
"str: \"\"\" Convert a Integer Decimal Number to a Binary",
"(most recent call last): ... TypeError: 'float' object cannot be",
"e in binary) return \"0b\" + \"\".join(str(e) for e in",
"if type(num) == float: raise TypeError(\"'float' object cannot be interpreted",
"TypeError: 'str' object cannot be interpreted as an integer \"\"\"",
"'0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>>",
">>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>>",
"return \"-0b\" + \"\".join(str(e) for e in binary) return \"0b\"",
"num >>= 1 if negative: return \"-0b\" + \"\".join(str(e) for",
"== float: raise TypeError(\"'float' object cannot be interpreted as an",
"error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most",
">>> # negatives work too >>> decimal_to_binary(-2) '-0b10' >>> #",
">>> decimal_to_binary(-2) '-0b10' >>> # other floats will error >>>",
"binary = [] while num > 0: binary.insert(0, num %",
"if type(num) == str: raise TypeError(\"'str' object cannot be interpreted",
"'0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives",
"cannot be interpreted as an integer >>> # strings will",
"negative: return \"-0b\" + \"\".join(str(e) for e in binary) return",
"doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError: 'float'",
"num > 0: binary.insert(0, num % 2) num >>= 1",
"call last): ... TypeError: 'float' object cannot be interpreted as",
"too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will error",
"object cannot be interpreted as an integer \"\"\" if type(num)",
"raise TypeError(\"'str' object cannot be interpreted as an integer\") if",
"well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call",
"\"0b\" + \"\".join(str(e) for e in binary) if __name__ ==",
"= False if num < 0: negative = True num",
"-> str: \"\"\" Convert a Integer Decimal Number to a",
"Decimal Number to a Binary Number as str. >>> decimal_to_binary(0)",
"interpreted as an integer\") if num == 0: return \"0b0\"",
"cannot be interpreted as an integer \"\"\" if type(num) ==",
"False if num < 0: negative = True num =",
"for e in binary) return \"0b\" + \"\".join(str(e) for e",
"0: negative = True num = -num binary = []",
"floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most",
"... TypeError: 'str' object cannot be interpreted as an integer",
"+ELLIPSIS Traceback (most recent call last): ... TypeError: 'str' object",
"[] while num > 0: binary.insert(0, num % 2) num",
"be interpreted as an integer\") if num == 0: return",
">>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last):",
"# doctest: +ELLIPSIS Traceback (most recent call last): ... TypeError:",
"+ \"\".join(str(e) for e in binary) return \"0b\" + \"\".join(str(e)",
"object cannot be interpreted as an integer\") if type(num) ==",
"return \"0b\" + \"\".join(str(e) for e in binary) if __name__",
"a Decimal Number to a Binary Number.\"\"\" def decimal_to_binary(num: int)",
"integer\") if type(num) == str: raise TypeError(\"'str' object cannot be",
"# strings will error as well >>> decimal_to_binary('0xfffff') # doctest:",
"an integer \"\"\" if type(num) == float: raise TypeError(\"'float' object",
"as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent",
"'0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011'",
"1 if negative: return \"-0b\" + \"\".join(str(e) for e in",
"== 0: return \"0b0\" negative = False if num <",
"if num == 0: return \"0b0\" negative = False if",
"cannot be interpreted as an integer\") if type(num) == str:",
"interpreted as an integer\") if type(num) == str: raise TypeError(\"'str'",
"< 0: negative = True num = -num binary =",
">>> # other floats will error >>> decimal_to_binary(16.16) # doctest:",
"decimal_to_binary(7) '0b111' >>> decimal_to_binary(35) '0b100011' >>> # negatives work too",
"float: raise TypeError(\"'float' object cannot be interpreted as an integer\")",
"as an integer\") if num == 0: return \"0b0\" negative",
"in binary) return \"0b\" + \"\".join(str(e) for e in binary)",
"TypeError(\"'float' object cannot be interpreted as an integer\") if type(num)",
"object cannot be interpreted as an integer\") if num ==",
"str: raise TypeError(\"'str' object cannot be interpreted as an integer\")",
"num % 2) num >>= 1 if negative: return \"-0b\"",
"negative = False if num < 0: negative = True",
"'-0b10' >>> # other floats will error >>> decimal_to_binary(16.16) #",
"> 0: binary.insert(0, num % 2) num >>= 1 if",
"will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback",
"+ELLIPSIS Traceback (most recent call last): ... TypeError: 'float' object",
"Number.\"\"\" def decimal_to_binary(num: int) -> str: \"\"\" Convert a Integer",
"will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent",
"'str' object cannot be interpreted as an integer \"\"\" if",
"to a Binary Number.\"\"\" def decimal_to_binary(num: int) -> str: \"\"\"",
"num == 0: return \"0b0\" negative = False if num",
">>> decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2)",
"other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback",
"as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7)",
"= [] while num > 0: binary.insert(0, num % 2)",
"# negatives work too >>> decimal_to_binary(-2) '-0b10' >>> # other",
"recent call last): ... TypeError: 'float' object cannot be interpreted",
"(most recent call last): ... TypeError: 'str' object cannot be",
"an integer\") if num == 0: return \"0b0\" negative =",
"% 2) num >>= 1 if negative: return \"-0b\" +",
">>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS Traceback (most recent call last):",
"Traceback (most recent call last): ... TypeError: 'float' object cannot",
"binary) return \"0b\" + \"\".join(str(e) for e in binary) if",
"decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10' >>> decimal_to_binary(7) '0b111' >>> decimal_to_binary(35)",
"strings will error as well >>> decimal_to_binary('0xfffff') # doctest: +ELLIPSIS",
"decimal_to_binary(35) '0b100011' >>> # negatives work too >>> decimal_to_binary(-2) '-0b10'",
"an integer\") if type(num) == str: raise TypeError(\"'str' object cannot",
"decimal_to_binary(num: int) -> str: \"\"\" Convert a Integer Decimal Number",
"Traceback (most recent call last): ... TypeError: 'str' object cannot",
"work too >>> decimal_to_binary(-2) '-0b10' >>> # other floats will",
"a Binary Number.\"\"\" def decimal_to_binary(num: int) -> str: \"\"\" Convert",
"decimal_to_binary(16.16) # doctest: +ELLIPSIS Traceback (most recent call last): ...",
"TypeError: 'float' object cannot be interpreted as an integer >>>",
"0: return \"0b0\" negative = False if num < 0:",
"\"\"\"Convert a Decimal Number to a Binary Number.\"\"\" def decimal_to_binary(num:",
"last): ... TypeError: 'float' object cannot be interpreted as an",
"for e in binary) if __name__ == \"__main__\": import doctest",
"cannot be interpreted as an integer\") if num == 0:",
"Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2) '0b10'",
"Decimal Number to a Binary Number.\"\"\" def decimal_to_binary(num: int) ->",
"= -num binary = [] while num > 0: binary.insert(0,",
"as an integer \"\"\" if type(num) == float: raise TypeError(\"'float'",
"0: binary.insert(0, num % 2) num >>= 1 if negative:",
"# other floats will error >>> decimal_to_binary(16.16) # doctest: +ELLIPSIS",
"integer \"\"\" if type(num) == float: raise TypeError(\"'float' object cannot",
"raise TypeError(\"'float' object cannot be interpreted as an integer\") if",
"be interpreted as an integer >>> # strings will error",
"a Binary Number as str. >>> decimal_to_binary(0) '0b0' >>> decimal_to_binary(2)",
"an integer >>> # strings will error as well >>>"
] |
[
"json import base64 import requests import logging class Network(): LOGIN_URL",
"= requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if response.text.find('v_failedTimes') is -1:",
"password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username, 'userPwd': <PASSWORD>}",
"LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language':",
"#-*- coding: utf-8 -*- import urllib.parse import json import base64",
"= jsonDict.get('serialNo') return self.heartBeatCyc def beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo':",
"if heartBeatCyc == None: raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc",
"jsonDict.get('heartBeatCyc') if heartBeatCyc == None: raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson))",
"logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text",
"username, 'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data,",
"heartBeatCyc == None: raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc =",
"= base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username, 'userPwd': <PASSWORD>} def login(self):",
"= { 'Accept-Language': 'en-US', 'Accept': 'text/html' } def __init__(self, username,",
"return self.heartBeatCyc def beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS,",
"username, password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username, 'userPwd':",
"b64Password = base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username, 'userPwd': <PASSWORD>} def",
"int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc def beat(self): response =",
"} def __init__(self, username, password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data =",
"import json import base64 import requests import logging class Network():",
"class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS =",
"'Accept': 'text/html' } def __init__(self, username, password): b64Password = base64.b64encode(bytes(password,'utf8'))",
"def login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText",
"= base64.b64decode(response.text + '==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson)",
"utf-8 -*- import urllib.parse import json import base64 import requests",
"== None: raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc)",
"def beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if",
"{ 'Accept-Language': 'en-US', 'Accept': 'text/html' } def __init__(self, username, password):",
"heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc == None: raise BaseException(responseJson) logging.info('login",
"self.heartBeatCyc = int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc def beat(self):",
"<PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3)",
"import requests import logging class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL",
"BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo')",
"'==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc')",
"seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc",
"self.data = {'userName': username, 'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response",
"def __init__(self, username, password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data = {'userName':",
"'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language': 'en-US', 'Accept': 'text/html' } def",
"'en-US', 'Accept': 'text/html' } def __init__(self, username, password): b64Password =",
"-*- import urllib.parse import json import base64 import requests import",
"'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS,",
"responseText = base64.b64decode(response.text + '==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict =",
"BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language': 'en-US', 'Accept': 'text/html'",
"data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text + '==') responseJson =",
"jsonDict.get('serialNo') return self.heartBeatCyc def beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo},",
"= 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language': 'en-US', 'Accept': 'text/html' }",
"+ '==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc =",
"requests import logging class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL =",
"= json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc == None: raise",
"self.heartBeatCyc def beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3)",
"logging class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS",
"= int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc def beat(self): response",
"response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text +",
"= {'userName': username, 'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response =",
"= requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text + '==')",
"data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if response.text.find('v_failedTimes') is -1: raise BaseException(response.text)",
"jsonDict = json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc == None:",
"requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text + '==') responseJson",
"base64 import requests import logging class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li'",
"self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc def beat(self): response = requests.post(Network.BEAT_URL,",
"COMMON_HERADERS = { 'Accept-Language': 'en-US', 'Accept': 'text/html' } def __init__(self,",
"headers=Network.COMMON_HERADERS, timeout=3) responseText = base64.b64decode(response.text + '==') responseJson = urllib.parse.unquote(responseText.decode('utf8'))",
"urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc ==",
"json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc == None: raise BaseException(responseJson)",
"coding: utf-8 -*- import urllib.parse import json import base64 import",
"logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return",
"%s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo = jsonDict.get('serialNo') return self.heartBeatCyc def",
"= jsonDict.get('heartBeatCyc') if heartBeatCyc == None: raise BaseException(responseJson) logging.info('login seccuss:",
"'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language': 'en-US', 'Accept':",
"urllib.parse import json import base64 import requests import logging class",
"raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo =",
"{'userName': username, 'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL,",
"base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username, 'userPwd': <PASSWORD>} def login(self): logging.info('login:%s'%(self.data))",
"= 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = { 'Accept-Language': 'en-US',",
"Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp' COMMON_HERADERS = {",
"'text/html' } def __init__(self, username, password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data",
"login(self): logging.info('login:%s'%(self.data)) response = requests.post(Network.LOGIN_URL, data=self.data, headers=Network.COMMON_HERADERS, timeout=3) responseText =",
"import base64 import requests import logging class Network(): LOGIN_URL =",
"= urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if heartBeatCyc",
"requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if response.text.find('v_failedTimes') is -1: raise",
"base64.b64decode(response.text + '==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc",
"response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if response.text.find('v_failedTimes') is",
"timeout=3) responseText = base64.b64decode(response.text + '==') responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict",
"responseJson = urllib.parse.unquote(responseText.decode('utf8')) jsonDict = json.loads(responseJson) heartBeatCyc = jsonDict.get('heartBeatCyc') if",
"#!/usr/bin/python3 #-*- coding: utf-8 -*- import urllib.parse import json import",
"import logging class Network(): LOGIN_URL = 'http://192.168.211.101/portal/pws?t=li' BEAT_URL = 'http://192.168.211.101/portal/page/doHeartBeat.jsp'",
"import urllib.parse import json import base64 import requests import logging",
"None: raise BaseException(responseJson) logging.info('login seccuss: %s'%(responseJson)) self.heartBeatCyc = int(heartBeatCyc) self.serialNo",
"beat(self): response = requests.post(Network.BEAT_URL, data={'serialNo': self.serialNo}, headers=Network.COMMON_HERADERS, timeout=3) if response.text.find('v_failedTimes')",
"__init__(self, username, password): b64Password = base64.b64encode(bytes(password,'utf8')) self.data = {'userName': username,",
"'Accept-Language': 'en-US', 'Accept': 'text/html' } def __init__(self, username, password): b64Password"
] |
[
"ValidTestCase as Valid class UseFstringRule(CstLintRule): MESSAGE: str = ( \"As",
"as Valid class UseFstringRule(CstLintRule): MESSAGE: str = ( \"As mentioned",
"class UseFstringRule(CstLintRule): MESSAGE: str = ( \"As mentioned in the",
"attr=m.Name(value=\"format\")) ), ): self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation) -> None:",
"-> None: if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) #",
"Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s'",
"Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw string value=%s' % val\"), ]",
"don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left, cst.SimpleString).evaluated_value, str",
"Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ] INVALID =",
"Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw string value=%s' %",
"from fixit import ValidTestCase as Valid class UseFstringRule(CstLintRule): MESSAGE: str",
"Invalid from fixit import ValidTestCase as Valid class UseFstringRule(CstLintRule): MESSAGE:",
"efficient.\" ) VALID = [ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"),",
"Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do not use printf",
"\"please do not use printf style formatting or `str.format()`. \"",
"as m from fixit import CstLintRule from fixit import InvalidTestCase",
") # SimpleString can be bytes and fstring don't support",
"value=%s' % val\"), ] def visit_Call(self, node: cst.Call) -> None:",
"None: if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString",
"[Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do not use",
"): self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation) -> None: if (",
"do not use printf style formatting or `str.format()`. \" +",
"to be \" + \"more readable and efficient.\" ) VALID",
"from fixit import InvalidTestCase as Invalid from fixit import ValidTestCase",
"# SimpleString can be bytes and fstring don't support bytes.",
"node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node) def visit_BinaryOperation(self, node:",
"SimpleString can be bytes and fstring don't support bytes. #",
"string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ] INVALID",
"None: if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node)",
"func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation) ->",
"\"more readable and efficient.\" ) VALID = [ Valid(\"assigned='string'; f'testing",
") VALID = [ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated'",
"\"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do not use printf style formatting",
"%s' % 'string'.encode('utf-8')\"), ] INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello,",
"VALID = [ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' +",
"import CstLintRule from fixit import InvalidTestCase as Invalid from fixit",
"Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ] INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"),",
"from fixit import CstLintRule from fixit import InvalidTestCase as Invalid",
"libcst as cst import libcst.matchers as m from fixit import",
"node: cst.Call) -> None: if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\"))",
"fixit import InvalidTestCase as Invalid from fixit import ValidTestCase as",
"[f-string](https://realpython.com/python-f-strings/) instead to be \" + \"more readable and efficient.\"",
"def visit_BinaryOperation(self, node: cst.BinaryOperation) -> None: if ( m.matches( node,",
"support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left, cst.SimpleString).evaluated_value, str )",
"the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do not",
"= [ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"),",
"can be bytes and fstring don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings",
"cst.Call) -> None: if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ),",
"formatting or `str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/) instead to be",
"+ \"more readable and efficient.\" ) VALID = [ Valid(\"assigned='string';",
"be bytes and fstring don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and",
"style formatting or `str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/) instead to",
"operator=m.Modulo()) ) # SimpleString can be bytes and fstring don't",
"# https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left, cst.SimpleString).evaluated_value, str ) ): self.report(node)",
"( \"As mentioned in the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \"",
"{assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"),",
"if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString can",
"= ( \"As mentioned in the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md),",
"import InvalidTestCase as Invalid from fixit import ValidTestCase as Valid",
"+ \"please do not use printf style formatting or `str.format()`.",
"val\"), ] def visit_Call(self, node: cst.Call) -> None: if m.matches(",
"'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ] INVALID = [ Invalid(\"'hello,",
"in the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do",
"str = ( \"As mentioned in the [Contributing Guidelines]\" +",
"+ \"Use [f-string](https://realpython.com/python-f-strings/) instead to be \" + \"more readable",
"not use printf style formatting or `str.format()`. \" + \"Use",
"and efficient.\" ) VALID = [ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple",
"visit_BinaryOperation(self, node: cst.BinaryOperation) -> None: if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(),",
"mentioned in the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please",
"), ): self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation) -> None: if",
"% 'string'.encode('utf-8')\"), ] INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s'",
"UseFstringRule(CstLintRule): MESSAGE: str = ( \"As mentioned in the [Contributing",
"instead to be \" + \"more readable and efficient.\" )",
"-> None: if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ):",
"import libcst.matchers as m from fixit import CstLintRule from fixit",
"and fstring don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left,",
"] INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"),",
"%s' % 'you'\"), Invalid(\"r'raw string value=%s' % val\"), ] def",
"{name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw string value=%s' % val\"),",
"Invalid(\"r'raw string value=%s' % val\"), ] def visit_Call(self, node: cst.Call)",
"\" + \"please do not use printf style formatting or",
"m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node) def visit_BinaryOperation(self,",
"InvalidTestCase as Invalid from fixit import ValidTestCase as Valid class",
"% val\"), ] def visit_Call(self, node: cst.Call) -> None: if",
"\" + \"more readable and efficient.\" ) VALID = [",
"% 'you'\"), Invalid(\"r'raw string value=%s' % val\"), ] def visit_Call(self,",
"fixit import ValidTestCase as Valid class UseFstringRule(CstLintRule): MESSAGE: str =",
"INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw",
"libcst.matchers as m from fixit import CstLintRule from fixit import",
"node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString can be bytes and",
"bytes and fstring don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance(",
"cst.BinaryOperation) -> None: if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) )",
"use printf style formatting or `str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/)",
"m from fixit import CstLintRule from fixit import InvalidTestCase as",
"cst import libcst.matchers as m from fixit import CstLintRule from",
"] def visit_Call(self, node: cst.Call) -> None: if m.matches( node,",
"[ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw string value=%s'",
"be \" + \"more readable and efficient.\" ) VALID =",
"fixit import CstLintRule from fixit import InvalidTestCase as Invalid from",
"visit_Call(self, node: cst.Call) -> None: if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(),",
"or `str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/) instead to be \"",
"'you'\"), Invalid(\"r'raw string value=%s' % val\"), ] def visit_Call(self, node:",
"[ Valid(\"assigned='string'; f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes",
"if m.matches( node, m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node) def",
"import libcst as cst import libcst.matchers as m from fixit",
"node: cst.BinaryOperation) -> None: if ( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo())",
"bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left, cst.SimpleString).evaluated_value, str ) ):",
"m.Call( func=m.Attribute(value=m.SimpleString(), attr=m.Name(value=\"format\")) ), ): self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation)",
"m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString can be bytes",
"( m.matches( node, m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString can be",
"Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ]",
"+ \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" + \"please do not use printf style",
"`str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/) instead to be \" +",
"fstring don't support bytes. # https://www.python.org/dev/peps/pep-0498/#no-binary-f-strings and isinstance( cst.ensure_type(node.left, cst.SimpleString).evaluated_value,",
"def visit_Call(self, node: cst.Call) -> None: if m.matches( node, m.Call(",
"readable and efficient.\" ) VALID = [ Valid(\"assigned='string'; f'testing {assigned}'\"),",
"f'testing {assigned}'\"), Valid(\"'simple string'\"), Valid(\"'concatenated' + 'string'\"), Valid(\"b'bytes %s' %",
"as Invalid from fixit import ValidTestCase as Valid class UseFstringRule(CstLintRule):",
"printf style formatting or `str.format()`. \" + \"Use [f-string](https://realpython.com/python-f-strings/) instead",
"+ 'string'\"), Valid(\"b'bytes %s' % 'string'.encode('utf-8')\"), ] INVALID = [",
"\"As mentioned in the [Contributing Guidelines]\" + \"(https://github.com/TheAlgorithms/Python/blob/master/CONTRIBUTING.md), \" +",
"\"Use [f-string](https://realpython.com/python-f-strings/) instead to be \" + \"more readable and",
"= [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' % 'you'\"), Invalid(\"r'raw string",
"string value=%s' % val\"), ] def visit_Call(self, node: cst.Call) ->",
"import ValidTestCase as Valid class UseFstringRule(CstLintRule): MESSAGE: str = (",
"'string'.encode('utf-8')\"), ] INVALID = [ Invalid(\"'hello, {name}'.format(name='you')\"), Invalid(\"'hello, %s' %",
"MESSAGE: str = ( \"As mentioned in the [Contributing Guidelines]\"",
"self.report(node) def visit_BinaryOperation(self, node: cst.BinaryOperation) -> None: if ( m.matches(",
"\" + \"Use [f-string](https://realpython.com/python-f-strings/) instead to be \" + \"more",
"as cst import libcst.matchers as m from fixit import CstLintRule",
"Valid class UseFstringRule(CstLintRule): MESSAGE: str = ( \"As mentioned in",
"CstLintRule from fixit import InvalidTestCase as Invalid from fixit import",
"m.BinaryOperation(left=m.SimpleString(), operator=m.Modulo()) ) # SimpleString can be bytes and fstring"
] |
[
"else: feature_this_round, hidden_feature_this_round = features, hidden_feature if self.params.label_transfer and self.params.grid_transformer:",
"== tf.estimator.ModeKeys.TRAIN) # extract bert hidden features inputs['model_input_mask'] = self.bert.get_input_mask()",
"call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode: str)",
"respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6],",
"= task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round",
"from .modeling import MultiModalBertModel from .params import BaseParams from .top",
"0, 'b_loss_multiplier': 1}] Output: { 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1,",
"'b_loss_multiplier': 1} # } features = inputs return_feature = {}",
"a lot of summaries to a Tensor (for TensorBoard visualization).\"\"\"",
"mlm might need word embedding from bert # build sub-model",
"logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer,",
"features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type = self.params.problem_type[problem] # if pretrain,",
"* [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type ==",
"metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer in self.top.top_layer_dict.items()}",
"for features_name in features: feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind) return",
"signatures, assign inputs accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs =",
"for one step of evaluation. This typically includes the forward",
"to calculate mean m_list = [] for metric in self.metrics:",
"Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode: str) -> Dict[str, tf.Tensor]:",
"return_dict = {} for problem_dict in self.params.run_problem_list: for problem in",
"accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params': self.params,",
"hidden_feature = inputs return_dict = {} for problem_dict in self.params.run_problem_list:",
"each problem chunk, we extract corresponding features and hidden features",
"= {} for problem_dict in self.params.run_problem_list: for problem in problem_dict:",
"as tf import transformers from .modeling import MultiModalBertModel from .params",
"SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain':",
"return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert features and dispatch",
"transformers from .modeling import MultiModalBertModel from .params import BaseParams from",
"self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars))",
"for m in self.metrics} def predict_step(self, data): return self(data, mode=tf.estimator.ModeKeys.PREDICT)",
"'pooled', 'all', 'embed', 'embed_table']: if logit_type == 'seq': # tensor,",
"hidden_feature: if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind,",
"'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() # Return",
"# Updates stateful loss metrics. self.compiled_loss( None, y_pred, None, regularization_losses=self.losses)",
"if pretrain, return pretrain logit if problem_type == 'pretrain': pretrain",
"hidden_feature_per_problem = self.body( inputs, mode) pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem),",
"'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}]",
"otherwise specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] #",
"# get features with ind == 1 if mode ==",
"feature_this_round return return_feature, return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to",
"'a_loss_multiplier': 1, 'b_loss_multiplier': 0} # 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0,",
"evaluation logic. This method is called by `Model.make_test_function`. This function",
"mathemetical logic for one step of evaluation. This typically includes",
"Cell from typing import Dict, Tuple from inspect import signature",
"tape: # Forward pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather",
"'embed_table']: if logit_type == 'seq': # tensor, [batch_size, seq_length, hidden_size]",
"if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0",
"= tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else:",
"in problem_dict: problem_type = self.params.problem_type[problem] # some layers has different",
"hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list())",
"logic for one step of evaluation. This typically includes the",
"the `Model`'s metrics are returned. \"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL)",
"a Tensor (for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var)",
"behind this # is to save computation for downstream processing.",
"hidden_feature[problem] problem_type = self.params.problem_type[problem] # if pretrain, return pretrain logit",
"main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings",
"'b_loss_multiplier': 0}, # {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] #",
"metric names to current value. # Note that it will",
"mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body( inputs, mode) pred_per_problem = self.top(",
"method is called by `Model.make_test_function`. This function should contain the",
"save computation for downstream processing. # For example, we have",
"behind this is to save computation for downstream processing. For",
"forward pass, loss calculation, and metrics updates. Configuration details for",
"elif logit_type == 'pooled': # tensor, [batch_size, hidden_size] hidden_feature[logit_type] =",
"metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name: m.result() for m in",
"name): \"\"\"Attach a lot of summaries to a Tensor (for",
"'all': # list, num_hidden_layers * [batch_size, seq_length, hidden_size] hidden_feature[logit_type] =",
"and mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try: # mask_lm_top",
"# Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top layer, aka",
"__all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from",
"== 'seq': # tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output()",
"self.top_layer_dict = {} for problem_dict in self.params.run_problem_list: for problem in",
"'params': self.params, 'problem_name': problem } for signature_name in layer_signature_name: if",
"Dict[str, tf.Tensor]: features, hidden_feature = inputs return_dict = {} for",
"in features: feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind) return feature_this_round, hidden_feature_this_round",
"save computation for downstream processing. For example, we have a",
"they're from problem a and b respectively: Input: [{'input_ids': [1,2,3],",
"get features with ind == 1 if mode == tf.estimator.ModeKeys.PREDICT:",
"batch of two instances and they're from # problem a",
"mask_lm_top(features, # hidden_feature, mode, 'dummy') # except ValueError: # pass",
"seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type == 'pooled': #",
"= {} for hidden_feature_name in hidden_feature: if hidden_feature_name != 'embed_table':",
"losses from all problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name,",
"Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict",
"raise ValueError( 'Label Transfer and grid transformer cannot be enabled",
"- mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var)",
"['seq', 'pooled', 'all', 'embed', 'embed_table']: if logit_type == 'seq': #",
"Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars) #",
"Dict[str, tf.Tensor], mode: str) -> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str,",
"self.params = params # initialize body model, aka transformers self.body",
"self.params.run_problem_list: for problem in problem_dict: if self.params.task_transformer: # hidden_feature =",
"test_step(self, data): \"\"\"The logic for one evaluation step. This method",
".utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach a lot",
"step. This method can be overridden to support custom evaluation",
"metric.name: continue if 'acc' in metric.name: m_list.append(metric.result()) if 'f1' in",
"self.params.problem_type[problem] # if pretrain, return pretrain logit if problem_type ==",
"def compile(self): super(BertMultiTask, self).compile() logger = tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr))",
"logit_type == 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() # for each problem",
"['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing import",
"1}] # Output: # { # 'a': {'input_ids': [1,2,3], 'a_loss_multiplier':",
"__init__(self, params: BaseParams, name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name) self.params =",
"problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0: return_loss = 0.0",
"method can be overridden to support custom evaluation logic. This",
"== 'all': # list, num_hidden_layers * [batch_size, seq_length, hidden_size] hidden_feature[logit_type]",
"'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} # 'b': {'input_ids':",
"from # problem a and b respectively: # Input: #",
"[4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} } \"\"\" def __init__(self, params:",
"None @tf.function def get_features_for_problem(self, features, hidden_feature, problem, mode): # get",
"[{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, # {'input_ids': [4,5,6], 'a_loss_multiplier':",
"1} # } features = inputs return_feature = {} return_hidden_feature",
"@tf.function def filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) ==",
"> 1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature, problem, mode)",
"import BaseParams from .top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel,",
"*how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings),",
"in self.metrics: if 'mean_acc' in metric.name: continue if 'acc' in",
"{} for hidden_feature_name in hidden_feature: if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name]",
"logit_type == 'seq': # tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type] =",
"{ 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b': {'input_ids':",
"# 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} # }",
"problem_type = self.params.problem_type[problem] # some layers has different signatures, assign",
"get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings =",
"features # and hidden features for that problem. The reason",
"that it will include the loss (tracked in self.metrics). return",
"record_ind) return feature_this_round, hidden_feature_this_round def call(self, inputs: Dict[str, tf.Tensor], mode:",
"be overridden. Arguments: data: A nested structure of `Tensor`s. Returns:",
"stateful loss metrics. self.compiled_loss( None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred,",
"features, hidden_feature, problem, mode) else: feature_this_round, hidden_feature_this_round = features, hidden_feature",
"and hidden features for that problem. The reason behind this",
"-> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _ = self.bert(inputs,",
"and grid transformer cannot be enabled in the same time.'",
"for metric in self.metrics: if 'mean_acc' in metric.name: continue if",
"= self.bert.get_all_encoder_layers() elif logit_type == 'embed': # for res connection",
"overridden. Arguments: data: A nested structure of `Tensor`s. Returns: A",
"in self.params.run_problem_list: for problem in problem_dict: problem_type = self.params.problem_type[problem] #",
"in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name: m.result() for m",
"and b respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0},",
"self.top.top_layer_dict.items()} metric_dict = {m.name: m.result() for m in self.metrics} #",
"params problem_type_layer = { 'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq,",
"is to save computation for downstream processing. For example, we",
"can also be overridden. Arguments: data: A nested structure of",
"names to current value. # Note that it will include",
"name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params = params self.bert = MultiModalBertModel(params=self.params) if",
"== 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() # for each problem chunk,",
"in the same time.' ) with tf.name_scope(problem): layer = self.top_layer_dict[problem]",
"in the same time.' ) if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem]",
"for downstream processing. For example, we have a batch of",
"= layer( (feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm and mode ==",
"The reason behind this is to save computation for downstream",
"MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for problem_dict in self.params.run_problem_list:",
"input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top = BertMultiTaskTop( params=self.params,",
"input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body( inputs,",
"Returns: A `dict` containing values that will be passed to",
"stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var))",
"hidden_feature_this_round = hidden_feature else: multiplier_name = '%s_loss_multiplier' % problem record_ind",
"hidden_feature_this_round = hidden_feature[problem] problem_type = self.params.problem_type[problem] # if pretrain, return",
"tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round = hidden_feature else: multiplier_name =",
"self.bert.get_all_encoder_layers() elif logit_type == 'embed': # for res connection hidden_feature[logit_type]",
"# is to save computation for downstream processing. # For",
"= feature_this_round return return_feature, return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model",
"def get_features_for_problem(self, features, hidden_feature, problem, mode): # get features with",
"PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for problem_dict",
"returned. \"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss",
"hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type == 'pooled': # tensor, [batch_size,",
"will include the loss (tracked in self.metrics). return return_dict def",
"'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round), mode)",
"tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try: # mask_lm_top = MaskLM(self.params) #",
"problem. The reason behind this is to save computation for",
"return_dict # Cell class BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams, name='BertMultiTask')",
"'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape(",
"# } features = inputs return_feature = {} return_hidden_feature =",
"} \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params",
"a and b respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier':",
"NotImplementedError if len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features,",
"= tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var",
"self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try: #",
"edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody',",
"params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params = params self.bert =",
"data): with tf.GradientTape() as tape: # Forward pass _ =",
"in metric_dict.items() if n != 'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict)",
"return_dict['augument_mask_lm'] = \\ # mask_lm_top(features, # hidden_feature, mode, 'dummy') #",
"processing. For example, we have a batch of two instances",
"rows to each problem_chunk. for each problem chunk, we extract",
"class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top layer, aka classification layer,",
"# metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer in",
"same time.' ) with tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem] =",
"problem } for signature_name in layer_signature_name: if signature_name == 'input_embeddings':",
"the same time.' ) with tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem]",
"problem in problem_dict: feature_this_round = features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type",
"return return_feature, return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create",
"in metric.name: m_list.append(metric.result()) if 'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list)",
"top layer, aka classification layer, for each problem. \"\"\" def",
"This typically includes the forward pass, loss calculation, and metrics",
"typically includes the forward pass, loss calculation, and metrics updates.",
"they're from # problem a and b respectively: # Input:",
"with ind == 1 if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round =",
"return pretrain logit if problem_type == 'pretrain': pretrain = self.top_layer_dict[problem]",
"EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ =",
"[1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, # {'input_ids': [4,5,6], 'a_loss_multiplier': 0,",
"and dispatch corresponding rows to each problem_chunk. for each problem",
"b respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids':",
"pass return return_dict # Cell class BertMultiTask(tf.keras.Model): def __init__(self, params:",
"# Return a dict mapping metric names to current value.",
"tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean)))",
"`tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_test_function`, which",
"which can also be overridden. Arguments: data: A nested structure",
"# problem a and b respectively: # Input: # [{'input_ids':",
"'b_loss_multiplier': 0} # 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}",
"inputs accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params':",
"mode) return pred_per_problem def compile(self): super(BertMultiTask, self).compile() logger = tf.get_logger()",
"'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict =",
"None) # get metrics to calculate mean m_list = []",
"feature_this_round, hidden_feature_this_round def call(self, inputs: Dict[str, tf.Tensor], mode: str) ->",
"different signatures, assign inputs accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs",
"# 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} # 'b':",
"[4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] # Output: # { #",
"if problem_type == 'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem] = pretrain(",
"'dummy') # except ValueError: # pass return return_dict # Cell",
"= self.top( (feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem def compile(self): super(BertMultiTask,",
"{ 'params': self.params, 'problem_name': problem } for signature_name in layer_signature_name:",
"weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with tf.GradientTape()",
"source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop',",
"inputs: Dict[str, tf.Tensor], mode: str) -> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str,",
"The reason behind this # is to save computation for",
"step of evaluation. This typically includes the forward pass, loss",
"Seq2Seq, SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var,",
"bert features and dispatch corresponding rows to each problem_chunk. for",
"hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round = {} for",
"= features hidden_feature_this_round = hidden_feature else: multiplier_name = '%s_loss_multiplier' %",
"self.compiled_loss( None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) # get",
"feature_this_round, hidden_feature_this_round = features, hidden_feature if self.params.label_transfer and self.params.grid_transformer: raise",
"ind == 1 if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round = features",
"0, 'b_loss_multiplier': 1} # } features = inputs return_feature =",
"= self.bert.get_sequence_output() elif logit_type == 'pooled': # tensor, [batch_size, hidden_size]",
"features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature = {}",
"is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left",
"{ 'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls':",
"computation for downstream processing. For example, we have a batch",
"= { 'params': self.params, 'problem_name': problem } for signature_name in",
"extract corresponding features # and hidden features for that problem.",
"with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev",
"layer_signature_name: if signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] =",
"Dict[str, tf.Tensor]]], mode: str) -> Dict[str, tf.Tensor]: features, hidden_feature =",
"== tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try: # mask_lm_top = MaskLM(self.params)",
"# top_layer in self.top.top_layer_dict.items()} metric_dict = {m.name: m.result() for m",
") self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with tf.GradientTape() as",
"call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body( inputs, mode) pred_per_problem",
"bert hidden features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature",
"ValueError( 'Label Transfer and grid transformer cannot be enabled in",
"problem chunk, we extract corresponding features and hidden features for",
"'Label Transfer and grid transformer cannot be enabled in the",
"'mean_acc' in metric.name: continue if 'acc' in metric.name: m_list.append(metric.result()) if",
"in self.top.top_layer_dict.items()} metric_dict = {m.name: m.result() for m in self.metrics}",
"features hidden_feature_this_round = hidden_feature else: multiplier_name = '%s_loss_multiplier' % problem",
"BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert features and dispatch corresponding rows",
"chunk, we extract corresponding features # and hidden features for",
"problem a and b respectively: # Input: # [{'input_ids': [1,2,3],",
"# mlm might need word embedding from bert # build",
"{} return_hidden_feature = {} for problem_dict in self.params.run_problem_list: for problem",
"== 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def",
"'a_loss_multiplier': 0, 'b_loss_multiplier': 1} } \"\"\" def __init__(self, params: BaseParams,",
"of summaries to a Tensor (for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name):",
"# {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] # Output: #",
"are returned. \"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful",
"= MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else:",
"= tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {} for hidden_feature_name in",
"hidden_feature_this_round), mode) return return_dict if self.params.label_transfer and self.params.grid_transformer: raise ValueError(",
"'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing import Dict, Tuple from",
"'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM",
"self.body = BertMultiTaskBody(params=self.params) # mlm might need word embedding from",
"gradients = tape.gradient(self.losses, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state(",
"`tf.distribute.Strategy` settings), should be left to `Model.make_test_function`, which can also",
"mode): # get features with ind == 1 if mode",
"features_name in features: feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind) return feature_this_round,",
"{'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer in self.top.top_layer_dict.items()} # metric_dict =",
"of two instances and they're from # problem a and",
"'pooled': # tensor, [batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer:",
"tensorflow as tf import transformers from .modeling import MultiModalBertModel from",
"for m in self.metrics} # Compute gradients trainable_vars = self.trainable_variables",
"overridden to support custom evaluation logic. This method is called",
"body model, aka transformers self.body = BertMultiTaskBody(params=self.params) # mlm might",
"def __init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor = None): super(BertMultiTaskTop,",
"calculation, and metrics updates. Configuration details for *how* this logic",
"y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss metrics. self.compiled_loss(",
"for each problem chunk, we extract corresponding features # and",
"inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs:",
"For example, we have a batch of two instances and",
"inputs_kwargs = { 'params': self.params, 'problem_name': problem } for signature_name",
"problem_name, top_layer in self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for",
"self.bert.get_sequence_output() elif logit_type == 'pooled': # tensor, [batch_size, hidden_size] hidden_feature[logit_type]",
"} features = inputs return_feature = {} return_hidden_feature = {}",
"tf import transformers from .modeling import MultiModalBertModel from .params import",
"{} for problem_dict in self.params.run_problem_list: for problem in problem_dict: if",
"MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {}",
"= self.params.problem_type[problem] # if pretrain, return pretrain logit if problem_type",
"self.metrics: if 'mean_acc' in metric.name: continue if 'acc' in metric.name:",
"to extract bert features and dispatch corresponding rows to each",
"= self.bert.get_embedding_table() # for each problem chunk, we extract corresponding",
"self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list) >",
"logit if problem_type == 'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem] =",
"tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss, features, problem): if",
".modeling import MultiModalBertModel from .params import BaseParams from .top import",
"mode) pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem def",
"from inspect import signature import tensorflow as tf import transformers",
"# Output: # { # 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1,",
"pretrain logit if problem_type == 'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem]",
"left to `Model.make_test_function`, which can also be overridden. Arguments: data:",
"feature_this_round = features hidden_feature_this_round = hidden_feature else: multiplier_name = '%s_loss_multiplier'",
"if logit_type == 'seq': # tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type]",
"= inputs return_feature = {} return_hidden_feature = {} for problem_dict",
"metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() # Return a dict mapping",
"mean m_list = [] for metric in self.metrics: if 'mean_acc'",
"= loss return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert",
"Output: { 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b':",
"call(self, inputs: Dict[str, tf.Tensor], mode: str) -> Tuple[Dict[str, Dict[str, tf.Tensor]],",
"# { # 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}",
"tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name]",
"Dict[str, Dict[str, tf.Tensor]]], mode: str) -> Dict[str, tf.Tensor]: features, hidden_feature",
"(feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem def compile(self): super(BertMultiTask, self).compile() logger",
"v in metric_dict.items() if n != 'mean_acc']) return_dict = metric_dict",
"None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) # get metrics",
"m.result() for m in self.metrics} # Compute gradients trainable_vars =",
"[{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0,",
"def train_step(self, data): with tf.GradientTape() as tape: # Forward pass",
"params # initialize body model, aka transformers self.body = BertMultiTaskBody(params=self.params)",
"Arguments: data: A nested structure of `Tensor`s. Returns: A `dict`",
"= params self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense(",
"self.bert.get_embedding_table() # for each problem chunk, we extract corresponding features",
"hidden_feature_this_round = features, hidden_feature if self.params.label_transfer and self.params.grid_transformer: raise ValueError(",
"and they're from problem a and b respectively: Input: [{'input_ids':",
"feature_this_round = {} for features_name in features: feature_this_round[features_name] = tf.gather_nd(",
"from .params import BaseParams from .top import (Classification, MultiLabelClassification, PreTrain,",
"for problem_name, # top_layer in self.top.top_layer_dict.items()} metric_dict = {m.name: m.result()",
"tf.Tensor]: features, hidden_feature = inputs return_dict = {} for problem_dict",
"'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() # for each problem chunk, we",
"for downstream processing. # For example, we have a batch",
"inputs return_feature = {} return_hidden_feature = {} for problem_dict in",
"'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} } \"\"\" def",
"for logit_type in ['seq', 'pooled', 'all', 'embed', 'embed_table']: if logit_type",
"processing. # For example, we have a batch of two",
"= BertMultiTaskBody(params=self.params) # mlm might need word embedding from bert",
"input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram',",
"from bert # build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model =",
"self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]],",
"this logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should",
"downstream processing. # For example, we have a batch of",
"Tuple from inspect import signature import tensorflow as tf import",
"Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _ = self.bert(inputs, mode ==",
"tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def",
"[4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} # } features = inputs",
"= tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps:",
"Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _ = self.bert(inputs, mode",
"to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ = ['variable_summaries', 'filter_loss',",
"'seq': # tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif",
"{}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 )",
"also be overridden. Arguments: data: A nested structure of `Tensor`s.",
"super(BertMultiTaskBody, self).__init__(name=name) self.params = params self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size:",
"record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {} for hidden_feature_name",
"'all', 'embed', 'embed_table']: if logit_type == 'seq': # tensor, [batch_size,",
"[v for n, v in metric_dict.items() if n != 'mean_acc'])",
"== 'pooled': # tensor, [batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if",
"elif logit_type == 'all': # list, num_hidden_layers * [batch_size, seq_length,",
"Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top layer, aka classification",
"# pass return return_dict # Cell class BertMultiTask(tf.keras.Model): def __init__(self,",
"__init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params = params self.bert",
"n, v in metric_dict.items() if n != 'mean_acc']) return_dict =",
"transformer cannot be enabled in the same time.' ) if",
"tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None @tf.function def get_features_for_problem(self,",
"This function should contain the mathemetical logic for one step",
"problem_type == 'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round,",
"def test_step(self, data): \"\"\"The logic for one evaluation step. This",
"problem_dict in self.params.run_problem_list: for problem in problem_dict: if self.params.task_transformer: #",
"logit_type == 'pooled': # tensor, [batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output()",
"# for each problem chunk, we extract corresponding features #",
"BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top layer, aka classification layer, for",
"return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert features and",
"hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type])",
"hidden_feature_per_problem), mode) return pred_per_problem def compile(self): super(BertMultiTask, self).compile() logger =",
"= self.mean_acc.result() # Return a dict mapping metric names to",
"tf.GradientTape() as tape: # Forward pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN)",
"stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss,",
"BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params = params self.bert = MultiModalBertModel(params=self.params)",
"enabled in the same time.' ) if self.params.grid_transformer: raise NotImplementedError",
"def filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0:",
"str) -> Dict[str, tf.Tensor]: features, hidden_feature = inputs return_dict =",
"import tensorflow as tf import transformers from .modeling import MultiModalBertModel",
"% problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {}",
"details for *how* this logic is run (e.g. `tf.function` and",
"with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev)",
"feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature, problem, mode) else: feature_this_round,",
"= self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm",
"hidden_feature_this_round def call(self, inputs: Dict[str, tf.Tensor], mode: str) -> Tuple[Dict[str,",
"features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0: return_loss =",
"enabled in the same time.' ) with tf.name_scope(problem): layer =",
"-> None: super(BertMultiTask, self).__init__(name=name) self.params = params # initialize body",
"'b_loss_multiplier': 1}] Output: { 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier':",
"input_embeddings = main_model.embeddings self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self,",
"mode == tf.estimator.ModeKeys.TRAIN) # extract bert hidden features inputs['model_input_mask'] =",
"axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round",
"= self.get_features_for_problem( features, hidden_feature, problem, mode) else: feature_this_round, hidden_feature_this_round =",
"pass, loss calculation, and metrics updates. Configuration details for *how*",
"\"\"\"The logic for one evaluation step. This method can be",
"None): super(BertMultiTaskTop, self).__init__(name=name) self.params = params problem_type_layer = { 'seq_tag':",
"= tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min',",
"we extract corresponding features # and hidden features for that",
"corresponding features # and hidden features for that problem. The",
"0.0 else: return_loss = loss return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model",
"specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell",
"signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params': self.params, 'problem_name': problem }",
"return_feature, return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top",
"tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _ = self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN)",
"0}, # {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] # Output:",
"values of the `Model`'s metrics are returned. \"\"\" y_pred =",
"PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model def",
"hidden features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature =",
"else: return_loss = loss return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to",
"can be overridden to support custom evaluation logic. This method",
"nested structure of `Tensor`s. Returns: A `dict` containing values that",
"BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name) self.params =",
"if n != 'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] =",
"tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier'",
"None: super(BertMultiTask, self).__init__(name=name) self.params = params # initialize body model,",
"problem]) == 0: return_loss = 0.0 else: return_loss = loss",
"return_feature[problem] = feature_this_round return return_feature, return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model):",
"= self.body( inputs, mode) pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem), mode)",
"problem_dict: if self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError if",
"= {m.name: m.result() for m in self.metrics} # Compute gradients",
"Configuration details for *how* this logic is run (e.g. `tf.function`",
"Typically, the values of the `Model`'s metrics are returned. \"\"\"",
"inputs, mode) pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem",
"values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values",
"'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier':",
"each problem_chunk. for each problem chunk, we extract corresponding features",
"inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body( inputs, mode) pred_per_problem =",
"{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier':",
"for res connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type == 'embed_table':",
"problem_type_layer = { 'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text':",
"inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature = {} for",
"tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps))",
"raise NotImplementedError if len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem(",
"= metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() # Return a dict",
"Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode: str) -> Dict[str,",
"trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for n,",
"`tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are returned.",
"self.mean_acc.update_state( m_list) return {m.name: m.result() for m in self.metrics} def",
"pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem def compile(self):",
"m.result() for m in self.metrics} def predict_step(self, data): return self(data,",
"hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif",
"= self.bert.get_token_type_ids() hidden_feature = {} for logit_type in ['seq', 'pooled',",
"and b respectively: # Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier': 1,",
"Dict[str, tf.Tensor]]]: _ = self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) # extract",
"len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature, problem,",
"'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for problem_dict in",
"= tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None @tf.function def",
"problem_type = self.params.problem_type[problem] # if pretrain, return pretrain logit if",
"for that problem. The reason behind this # is to",
"that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of",
"(feature_this_round, hidden_feature_this_round), mode) return return_dict if self.params.label_transfer and self.params.grid_transformer: raise",
"be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s",
"'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} }",
"= params # initialize body model, aka transformers self.body =",
"{'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] # Output: # {",
"self.params.problem_type[problem] # some layers has different signatures, assign inputs accordingly",
"layer( (feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN:",
"= main_model.embeddings self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self, inputs,",
"corresponding features and hidden features for that problem. The reason",
"extract bert hidden features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids()",
"= self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round), mode) return return_dict",
"variable_summaries(var, name): \"\"\"Attach a lot of summaries to a Tensor",
"of the `Model`'s metrics are returned. \"\"\" y_pred = self(data,",
"get_features_for_problem(self, features, hidden_feature, problem, mode): # get features with ind",
"(Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model,",
"self.bert.get_token_type_ids() hidden_feature = {} for logit_type in ['seq', 'pooled', 'all',",
"instances and they're from # problem a and b respectively:",
"mode) if self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError #",
"self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for n, v in metric_dict.items() if",
"var) @tf.function def filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem])",
"= hidden_feature[problem] problem_type = self.params.problem_type[problem] # if pretrain, return pretrain",
"= MaskLM(self.params) # return_dict['augument_mask_lm'] = \\ # mask_lm_top(features, # hidden_feature,",
"m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name: m.result() for m in self.metrics}",
"mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss metrics. self.compiled_loss( None, y_pred, None,",
"metric.name: m_list.append(metric.result()) if 'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return",
"Forward pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses from",
"num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data):",
"return_dict[self.mean_acc.name] = self.mean_acc.result() # Return a dict mapping metric names",
"time.' ) with tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem] = layer(",
"will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the",
"BertMultiTaskBody(params=self.params) # mlm might need word embedding from bert #",
"gather losses from all problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for",
"problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params': self.params, 'problem_name': problem } for",
"to save computation for downstream processing. For example, we have",
"a batch of two instances and they're from # problem",
"problem, mode): # get features with ind == 1 if",
"self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature = {} for logit_type in",
"contain the mathemetical logic for one step of evaluation. This",
"this # is to save computation for downstream processing. #",
"= hidden_feature else: multiplier_name = '%s_loss_multiplier' % problem record_ind =",
"= '%s_loss_multiplier' % problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round",
"hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ),",
"downstream processing. For example, we have a batch of two",
"else: multiplier_name = '%s_loss_multiplier' % problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]),",
"tf.reduce_sum(top_layer.losses) for problem_name, top_layer in self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name):",
"be overridden to support custom evaluation logic. This method is",
"be enabled in the same time.' ) with tf.name_scope(problem): layer",
"problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {} for",
"features = inputs return_feature = {} return_hidden_feature = {} for",
"NotImplementedError # try: # mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm'] =",
"lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler",
"(tracked in self.metrics). return return_dict def test_step(self, data): \"\"\"The logic",
"mode) return return_dict if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label",
"from .top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from",
"self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc",
"regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) # get metrics to calculate mean",
"tf.bool)) hidden_feature_this_round = {} for hidden_feature_name in hidden_feature: if hidden_feature_name",
"dispatch corresponding rows to each problem_chunk. for each problem chunk,",
"tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {} for hidden_feature_name in hidden_feature: if",
"= self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss metrics. self.compiled_loss( None,",
"tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer in self.top.top_layer_dict.items()} metric_dict = {m.name:",
"two instances and they're from # problem a and b",
"'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, # {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier':",
"(unless otherwise specified). __all__ = ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask']",
"_ = get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings",
"a dict mapping metric names to current value. # Note",
"# and hidden features for that problem. The reason behind",
"extract corresponding features and hidden features for that problem. The",
"for each problem. \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings:",
"try: # mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm'] = \\ #",
"a and b respectively: # Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier':",
"return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() # Return a dict mapping metric",
"metric in self.metrics: if 'mean_acc' in metric.name: continue if 'acc'",
"self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None @tf.function",
"the same time.' ) if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] =",
"'pretrain': PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for",
"y_pred, None) # get metrics to calculate mean m_list =",
"model, aka transformers self.body = BertMultiTaskBody(params=self.params) # mlm might need",
"} for signature_name in layer_signature_name: if signature_name == 'input_embeddings': inputs_kwargs.update(",
"initialize body model, aka transformers self.body = BertMultiTaskBody(params=self.params) # mlm",
"respectively: # Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0},",
"self.body( inputs, mode) pred_per_problem = self.top( (feature_per_problem, hidden_feature_per_problem), mode) return",
"transformers self.body = BertMultiTaskBody(params=self.params) # mlm might need word embedding",
"is called by `Model.make_test_function`. This function should contain the mathemetical",
"data: A nested structure of `Tensor`s. Returns: A `dict` containing",
"lot of summaries to a Tensor (for TensorBoard visualization).\"\"\" with",
"AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise",
"(e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to `Model.make_test_function`,",
"{}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps,",
"Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier':",
"problem chunk, we extract corresponding features # and hidden features",
"# tensor, [batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type]",
"self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer",
"two instances and they're from problem a and b respectively:",
"self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] = feature_this_round return",
"tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode: str) -> Dict[str, tf.Tensor]: features,",
"multiplier_name = '%s_loss_multiplier' % problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool))",
"hidden_feature_this_round return_feature[problem] = feature_this_round return return_feature, return_hidden_feature # Cell class",
"layer = self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round), mode) if",
"self.compiled_metrics.update_state(None, y_pred, None) # get metrics to calculate mean m_list",
"create top layer, aka classification layer, for each problem. \"\"\"",
"each problem. \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor",
"res connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type == 'embed_table': hidden_feature[logit_type]",
"include the loss (tracked in self.metrics). return return_dict def test_step(self,",
"tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round = {} for hidden_feature_name in hidden_feature:",
"= get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top",
"mode: str) -> Dict[str, tf.Tensor]: features, hidden_feature = inputs return_dict",
"in layer_signature_name: if signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem]",
"loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer in self.top.top_layer_dict.items()} #",
"= None): super(BertMultiTaskTop, self).__init__(name=name) self.params = params problem_type_layer = {",
"compile(self): super(BertMultiTask, self).compile() logger = tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train",
"# except ValueError: # pass return return_dict # Cell class",
"hidden_feature[hidden_feature_name] feature_this_round = {} for features_name in features: feature_this_round[features_name] =",
"computation for downstream processing. # For example, we have a",
"self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu)",
"= params problem_type_layer = { 'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag':",
"if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round = hidden_feature",
"metric_dict.items() if n != 'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name]",
"# Cell class BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams, name='BertMultiTask') ->",
"example, we have a batch of two instances and they're",
"corresponding rows to each problem_chunk. for each problem chunk, we",
"'b_loss_multiplier': 1}] # Output: # { # 'a': {'input_ids': [1,2,3],",
"some layers has different signatures, assign inputs accordingly layer_signature_name =",
"inputs return_dict = {} for problem_dict in self.params.run_problem_list: for problem",
"TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with",
"return return_dict if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer",
"# mask_lm_top(features, # hidden_feature, mode, 'dummy') # except ValueError: #",
"steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01",
"value. # Note that it will include the loss (tracked",
"in metric.name: continue if 'acc' in metric.name: m_list.append(metric.result()) if 'f1'",
"problem a and b respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier': 1,",
"inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode: str) ->",
"aka transformers self.body = BertMultiTaskBody(params=self.params) # mlm might need word",
".top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils",
"SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name):",
"[batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type == 'pooled':",
"loss (tracked in self.metrics). return return_dict def test_step(self, data): \"\"\"The",
"tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0: return_loss = 0.0 else: return_loss",
"with tf.GradientTape() as tape: # Forward pass _ = self(data,",
"get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach a lot of summaries",
"tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var))",
"params: BaseParams, name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name) self.params = params",
"connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type == 'embed_table': hidden_feature[logit_type] =",
"tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round), mode)",
"m in self.metrics} # Compute gradients trainable_vars = self.trainable_variables gradients",
"BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams, name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name)",
"reason behind this # is to save computation for downstream",
"\"\"\"Attach a lot of summaries to a Tensor (for TensorBoard",
"# gather losses from all problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses)",
"hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round = {} for features_name",
"Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM }",
"typing import Dict, Tuple from inspect import signature import tensorflow",
"import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach a lot of",
"'problem_name': problem } for signature_name in layer_signature_name: if signature_name ==",
"\"\"\"Model to extract bert features and dispatch corresponding rows to",
"trainable_vars)) self.mean_acc.update_state( [v for n, v in metric_dict.items() if n",
"import transformers from .modeling import MultiModalBertModel from .params import BaseParams",
"Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, # {'input_ids':",
"layers has different signatures, assign inputs accordingly layer_signature_name = signature(",
"MaskLM(self.params) # return_dict['augument_mask_lm'] = \\ # mask_lm_top(features, # hidden_feature, mode,",
"features, hidden_feature = inputs return_dict = {} for problem_dict in",
"BaseParams, name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name) self.params = params #",
"be enabled in the same time.' ) if self.params.grid_transformer: raise",
"logit_type == 'all': # list, num_hidden_layers * [batch_size, seq_length, hidden_size]",
"ValueError: # pass return return_dict # Cell class BertMultiTask(tf.keras.Model): def",
"{} for logit_type in ['seq', 'pooled', 'all', 'embed', 'embed_table']: if",
"pretrain = self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round), mode) return",
"MultiModalBertModel from .params import BaseParams from .top import (Classification, MultiLabelClassification,",
"'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing import Dict, Tuple",
"[batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer(",
"{ # 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} #",
"return {m.name: m.result() for m in self.metrics} def predict_step(self, data):",
"'embed', 'embed_table']: if logit_type == 'seq': # tensor, [batch_size, seq_length,",
"_ = self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses from all problems",
"_ = self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) # extract bert hidden",
"super(BertMultiTask, self).compile() logger = tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps:",
"'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing import Dict,",
"File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__ = ['variable_summaries',",
"= self.bert.get_embedding_output() elif logit_type == 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() #",
"`Model`'s metrics are returned. \"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) #",
"def __init__(self, params: BaseParams, name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name) self.params",
"super(BertMultiTaskTop, self).__init__(name=name) self.params = params problem_type_layer = { 'seq_tag': SequenceLabel,",
"bert # build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model)",
"tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with tf.GradientTape() as tape: # Forward",
"loss metrics. self.compiled_loss( None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None)",
"MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model",
"from .utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach a",
"by `Model.make_test_function`. This function should contain the mathemetical logic for",
"calculate mean m_list = [] for metric in self.metrics: if",
"in self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, #",
"tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss, features, problem):",
"{'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output: { 'a': {'input_ids':",
"hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type == 'embed': # for res",
"should contain the mathemetical logic for one step of evaluation.",
"# Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars)",
"of two instances and they're from problem a and b",
"self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None",
"hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type == 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table()",
"logic for one evaluation step. This method can be overridden",
"for each problem chunk, we extract corresponding features and hidden",
"'%s_loss_multiplier' % problem record_ind = tf.where(tf.cast( tf.squeeze(features[multiplier_name]), tf.bool)) hidden_feature_this_round =",
"'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain,",
"metric_dict = {m.name: m.result() for m in self.metrics} # Compute",
"layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params': self.params, 'problem_name':",
"m_list.append(metric.result()) if 'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name:",
"= self.params.problem_type[problem] # some layers has different signatures, assign inputs",
"\"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss metrics.",
".params import BaseParams from .top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq,",
"{'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} } \"\"\" def __init__(self,",
"1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature, problem, mode) else:",
"Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm':",
"if signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type](",
"mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(",
"inspect import signature import tensorflow as tf import transformers from",
"task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round =",
"= {} for features_name in features: feature_this_round[features_name] = tf.gather_nd( features[features_name],",
"super(BertMultiTask, self).__init__(name=name) self.params = params # initialize body model, aka",
"problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer in self.top.top_layer_dict.items()}",
"self).__init__(name=name) self.params = params self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer",
"import MultiModalBertModel from .params import BaseParams from .top import (Classification,",
"self.params = params problem_type_layer = { 'seq_tag': SequenceLabel, 'cls': Classification,",
"= self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses from all problems loss_dict",
"settings), should be left to `Model.make_test_function`, which can also be",
"# hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list) > 1:",
"else: self.custom_pooled_layer = None @tf.function def get_features_for_problem(self, features, hidden_feature, problem,",
"tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss, features,",
"% problem]) == 0: return_loss = 0.0 else: return_loss =",
"'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name: m.result() for",
"from all problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer",
"return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() # Return a",
"and they're from # problem a and b respectively: #",
"if self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list)",
"reason behind this is to save computation for downstream processing.",
"classification layer, for each problem. \"\"\" def __init__(self, params: BaseParams,",
"name='BertMultiTask') -> None: super(BertMultiTask, self).__init__(name=name) self.params = params # initialize",
"MaskLM) from .utils import get_embedding_table_from_model, get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach",
"Tensor (for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean',",
"self.params.grid_transformer: raise ValueError( 'Label Transfer and grid transformer cannot be",
"one evaluation step. This method can be overridden to support",
"self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates stateful loss metrics. self.compiled_loss( None, y_pred,",
"import signature import tensorflow as tf import transformers from .modeling",
"instances and they're from problem a and b respectively: Input:",
"hidden_feature_this_round), mode) if self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError",
"it will include the loss (tracked in self.metrics). return return_dict",
"to each problem_chunk. for each problem chunk, we extract corresponding",
"params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name) self.params",
"# hidden_feature, mode, 'dummy') # except ValueError: # pass return",
"raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] = feature_this_round return return_feature,",
"if len(self.params.run_problem_list) > 1: feature_this_round, hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature,",
"self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem,",
"hidden_feature if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer and",
"`Model.make_test_function`, which can also be overridden. Arguments: data: A nested",
"for problem in problem_dict: feature_this_round = features[problem] hidden_feature_this_round = hidden_feature[problem]",
"def __init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params = params",
"# list, num_hidden_layers * [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers()",
"a batch of two instances and they're from problem a",
"'embed': # for res connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type",
"train_step(self, data): with tf.GradientTape() as tape: # Forward pass _",
"n != 'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result()",
"problem_dict in self.params.run_problem_list: for problem in problem_dict: feature_this_round = features[problem]",
"need word embedding from bert # build sub-model _ =",
"logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer(",
"= transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc')",
"self.custom_pooled_layer = None @tf.function def get_features_for_problem(self, features, hidden_feature, problem, mode):",
"tf.Tensor], mode: str) -> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]:",
"= \\ # mask_lm_top(features, # hidden_feature, mode, 'dummy') # except",
"1, 'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}",
"features and dispatch corresponding rows to each problem_chunk. for each",
"includes the forward pass, loss calculation, and metrics updates. Configuration",
"layer, aka classification layer, for each problem. \"\"\" def __init__(self,",
"pretrain( (feature_this_round, hidden_feature_this_round), mode) return return_dict if self.params.label_transfer and self.params.grid_transformer:",
"of `Tensor`s. Returns: A `dict` containing values that will be",
"list, num_hidden_layers * [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif",
"from problem a and b respectively: Input: [{'input_ids': [1,2,3], 'a_loss_multiplier':",
"= BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem",
"extract bert features and dispatch corresponding rows to each problem_chunk.",
"tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var -",
"trainable_vars = self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars) # Update weights",
"0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} } \"\"\"",
"for hidden_feature_name in hidden_feature: if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] =",
"[batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type == 'embed':",
"= self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) # extract bert hidden features",
"y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) # get metrics to",
"in ['seq', 'pooled', 'all', 'embed', 'embed_table']: if logit_type == 'seq':",
"self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with tf.GradientTape() as tape:",
"return pred_per_problem def compile(self): super(BertMultiTask, self).compile() logger = tf.get_logger() logger.info('Initial",
"{m.name: m.result() for m in self.metrics} # Compute gradients trainable_vars",
"for problem_dict in self.params.run_problem_list: for problem in problem_dict: if self.params.task_transformer:",
"aka classification layer, for each problem. \"\"\" def __init__(self, params:",
"{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} # 'b': {'input_ids': [4,5,6],",
"features with ind == 1 if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round",
"metrics. self.compiled_loss( None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) #",
"# [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, # {'input_ids': [4,5,6],",
"1, 'b_loss_multiplier': 0}, # {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}]",
"this is to save computation for downstream processing. For example,",
"we have a batch of two instances and they're from",
"in problem_dict: if self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError",
"build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings",
"self.top( (feature_per_problem, hidden_feature_per_problem), mode) return pred_per_problem def compile(self): super(BertMultiTask, self).compile()",
"in self.params.run_problem_list: for problem in problem_dict: feature_this_round = features[problem] hidden_feature_this_round",
"to support custom evaluation logic. This method is called by",
"the forward pass, loss calculation, and metrics updates. Configuration details",
"chunk, we extract corresponding features and hidden features for that",
"return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] = feature_this_round return return_feature, return_hidden_feature #",
"get metrics to calculate mean m_list = [] for metric",
"str) -> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _ =",
"batch of two instances and they're from problem a and",
"Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for n, v in",
"mode=tf.estimator.ModeKeys.TRAIN) # gather losses from all problems loss_dict = {'{}_loss'.format(problem_name):",
"that problem. The reason behind this is to save computation",
"hidden_feature, problem, mode): # get features with ind == 1",
"= { 'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq,",
"mode, 'dummy') # except ValueError: # pass return return_dict #",
"__init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name)",
"return_hidden_feature = {} for problem_dict in self.params.run_problem_list: for problem in",
"input_embeddings: tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name) self.params = params problem_type_layer",
"of evaluation. This typically includes the forward pass, loss calculation,",
"== 0: return_loss = 0.0 else: return_loss = loss return",
"have a batch of two instances and they're from problem",
"to `Model.make_test_function`, which can also be overridden. Arguments: data: A",
"self.mean_acc.update_state( [v for n, v in metric_dict.items() if n !=",
"embedding from bert # build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model",
"None, regularization_losses=self.losses) self.compiled_metrics.update_state(None, y_pred, None) # get metrics to calculate",
"A nested structure of `Tensor`s. Returns: A `dict` containing values",
"hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] =",
"@tf.function def get_features_for_problem(self, features, hidden_feature, problem, mode): # get features",
"hidden_feature, mode, 'dummy') # except ValueError: # pass return return_dict",
"init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self,",
"1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output:",
"class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert features and dispatch corresponding",
"word embedding from bert # build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model)",
"= tape.gradient(self.losses, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v",
"self).__init__(name=name) self.params = params problem_type_layer = { 'seq_tag': SequenceLabel, 'cls':",
"problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for problem_dict in self.params.run_problem_list: for problem",
"== tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round = hidden_feature else: multiplier_name",
"assign inputs accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = {",
"if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer =",
"= self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients,",
"one step of evaluation. This typically includes the forward pass,",
"if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] = feature_this_round",
"if self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try:",
"# Forward pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses",
"Return a dict mapping metric names to current value. #",
"pretrain, return pretrain logit if problem_type == 'pretrain': pretrain =",
"This method is called by `Model.make_test_function`. This function should contain",
"`Model.make_test_function`. This function should contain the mathemetical logic for one",
"gradients trainable_vars = self.trainable_variables gradients = tape.gradient(self.losses, trainable_vars) # Update",
"seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type == 'embed': #",
"each problem chunk, we extract corresponding features # and hidden",
"# Cell from typing import Dict, Tuple from inspect import",
"the loss (tracked in self.metrics). return return_dict def test_step(self, data):",
"might need word embedding from bert # build sub-model _",
"# mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm'] = \\ # mask_lm_top(features,",
"Updates stateful loss metrics. self.compiled_loss( None, y_pred, None, regularization_losses=self.losses) self.compiled_metrics.update_state(None,",
"def call(self, inputs: Dict[str, tf.Tensor], mode: str) -> Tuple[Dict[str, Dict[str,",
"= self.bert.get_input_mask() inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature = {} for logit_type",
"!= 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name], record_ind, axis=0 ), axis=1)",
"'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output: {",
"name='BertMultiTaskTop', input_embeddings: tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name) self.params = params",
"for n, v in metric_dict.items() if n != 'mean_acc']) return_dict",
"Cell class BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams, name='BertMultiTask') -> None:",
"in self.metrics). return return_dict def test_step(self, data): \"\"\"The logic for",
"= {} for logit_type in ['seq', 'pooled', 'all', 'embed', 'embed_table']:",
"problem. The reason behind this # is to save computation",
"input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs: Tuple[Dict[str, Dict[str,",
"problem_dict: feature_this_round = features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type = self.params.problem_type[problem]",
"Dict[str, Dict[str, tf.Tensor]]]: _ = self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) #",
"hidden_feature[logit_type]) elif logit_type == 'all': # list, num_hidden_layers * [batch_size,",
"get_transformer_main_model def variable_summaries(var, name): \"\"\"Attach a lot of summaries to",
"in hidden_feature: if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather( hidden_feature[hidden_feature_name],",
"= problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str,",
"mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max', tf.reduce_max(input_tensor=var)) tf.compat.v1.summary.scalar('min', tf.reduce_min(input_tensor=var)) tf.compat.v1.summary.histogram('histogram', var) @tf.function",
"self).__init__(name=name) self.params = params # initialize body model, aka transformers",
"= {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer in self.top.top_layer_dict.items()} metric_dict",
"(feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm and mode == tf.estimator.ModeKeys.TRAIN: raise",
"!= 'mean_acc']) return_dict = metric_dict return_dict.update(loss_dict) return_dict[self.mean_acc.name] = self.mean_acc.result() #",
"and metrics updates. Configuration details for *how* this logic is",
"MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer",
"to current value. # Note that it will include the",
"signature import tensorflow as tf import transformers from .modeling import",
"for one evaluation step. This method can be overridden to",
"containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the",
"mode == tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round = hidden_feature else:",
"logit_type in ['seq', 'pooled', 'all', 'embed', 'embed_table']: if logit_type ==",
"loss return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract bert features",
"= self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type == 'all': # list, num_hidden_layers",
"summaries to a Tensor (for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean",
"all problems loss_dict = {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer in",
"in self.metrics} # Compute gradients trainable_vars = self.trainable_variables gradients =",
"return_hidden_feature # Cell class BertMultiTaskTop(tf.keras.Model): \"\"\"Model to create top layer,",
"mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm'] = \\ # mask_lm_top(features, #",
"steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr,",
"params=self.params, input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body(",
"mean) with tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev',",
"Transfer and grid transformer cannot be enabled in the same",
"signature_name in layer_signature_name: if signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings})",
"= tf.gather_nd( features[features_name], record_ind) return feature_this_round, hidden_feature_this_round def call(self, inputs:",
"return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round), mode) return return_dict if self.params.label_transfer",
"= hidden_feature_this_round return_feature[problem] = feature_this_round return return_feature, return_hidden_feature # Cell",
"self.params, 'problem_name': problem } for signature_name in layer_signature_name: if signature_name",
"logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps,",
"# if pretrain, return pretrain logit if problem_type == 'pretrain':",
"= features, hidden_feature if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label",
"tf.Tensor]]]: _ = self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) # extract bert",
"`dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically,",
"with tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round),",
"self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type == 'all': # list, num_hidden_layers *",
"in self.params.run_problem_list: for problem in problem_dict: if self.params.task_transformer: # hidden_feature",
"self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round), mode) return return_dict if",
"m_list = [] for metric in self.metrics: if 'mean_acc' in",
"self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses from all problems loss_dict =",
"logger = tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup",
"# input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top = BertMultiTaskTop(",
"to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics are",
"1, 'b_loss_multiplier': 0} # 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier':",
"hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type == 'pooled': # tensor,",
"[] for metric in self.metrics: if 'mean_acc' in metric.name: continue",
"problem_name, # top_layer in self.top.top_layer_dict.items()} metric_dict = {m.name: m.result() for",
"A `dict` containing values that will be passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`.",
"{}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps)) logger.info('Warmup steps: {}'.format(self.params.num_warmup_steps)) self.optimizer, self.lr_scheduler =",
"hidden_feature = {} for logit_type in ['seq', 'pooled', 'all', 'embed',",
"self.params.run_problem_list: for problem in problem_dict: feature_this_round = features[problem] hidden_feature_this_round =",
"if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0: return_loss = 0.0 else:",
"problem. \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor =",
"# try: # mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm'] = \\",
"return_loss = loss return return_loss class BertMultiTaskBody(tf.keras.Model): \"\"\"Model to extract",
"problem_dict in self.params.run_problem_list: for problem in problem_dict: problem_type = self.params.problem_type[problem]",
"{'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name, # top_layer in self.top.top_layer_dict.items()} metric_dict =",
"1}] Output: { 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}",
"for *how* this logic is run (e.g. `tf.function` and `tf.distribute.Strategy`",
"weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for n, v in metric_dict.items()",
"sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings =",
"pred_per_problem def compile(self): super(BertMultiTask, self).compile() logger = tf.get_logger() logger.info('Initial lr:",
"b respectively: # Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier':",
"as tape: # Forward pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN) #",
"return feature_this_round, hidden_feature_this_round def call(self, inputs: Dict[str, tf.Tensor], mode: str)",
"time.' ) if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem]",
"{m.name: m.result() for m in self.metrics} def predict_step(self, data): return",
"0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output: { 'a':",
"return_loss = 0.0 else: return_loss = loss return return_loss class",
"= inputs return_dict = {} for problem_dict in self.params.run_problem_list: for",
"inputs['model_token_type_ids'] = self.bert.get_token_type_ids() hidden_feature = {} for logit_type in ['seq',",
"# for res connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif logit_type ==",
"= {} return_hidden_feature = {} for problem_dict in self.params.run_problem_list: for",
"problem, mode) else: feature_this_round, hidden_feature_this_round = features, hidden_feature if self.params.label_transfer",
"hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round = {} for features_name in features:",
"visualization).\"\"\" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'):",
"self.get_features_for_problem( features, hidden_feature, problem, mode) else: feature_this_round, hidden_feature_this_round = features,",
"to create top layer, aka classification layer, for each problem.",
"hidden_feature, problem, mode) else: feature_this_round, hidden_feature_this_round = features, hidden_feature if",
"self.metrics). return return_dict def test_step(self, data): \"\"\"The logic for one",
"be left to `Model.make_test_function`, which can also be overridden. Arguments:",
"[4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output: { 'a': {'input_ids': [1,2,3],",
"1} } \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name)",
"hidden_feature_this_round = {} for hidden_feature_name in hidden_feature: if hidden_feature_name !=",
"if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type == 'all':",
"tape.gradient(self.losses, trainable_vars) # Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for",
"is to save computation for downstream processing. # For example,",
"tf.gather_nd( features[features_name], record_ind) return feature_this_round, hidden_feature_this_round def call(self, inputs: Dict[str,",
"tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type ==",
"tf.compat.v1.summary.histogram('histogram', var) @tf.function def filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' %",
"# build sub-model _ = get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) #",
"self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type ==",
"problem_chunk. for each problem chunk, we extract corresponding features and",
"features for that problem. The reason behind this is to",
"else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round = {} for features_name in",
"for that problem. The reason behind this is to save",
"# get metrics to calculate mean m_list = [] for",
"hidden features for that problem. The reason behind this #",
"for signature_name in layer_signature_name: if signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name:",
"[1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier':",
"that problem. The reason behind this # is to save",
"cannot be enabled in the same time.' ) with tf.name_scope(problem):",
"features[features_name], record_ind) return feature_this_round, hidden_feature_this_round def call(self, inputs: Dict[str, tf.Tensor],",
"{} for problem_dict in self.params.run_problem_list: for problem in problem_dict: feature_this_round",
"function should contain the mathemetical logic for one step of",
"and self.params.grid_transformer: raise ValueError( 'Label Transfer and grid transformer cannot",
"hidden_feature[logit_type] = self.bert.get_embedding_table() # for each problem chunk, we extract",
"self.mean_acc.result() # Return a dict mapping metric names to current",
"should be left to `Model.make_test_function`, which can also be overridden.",
"params self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer = tf.keras.layers.Dense( self.params.custom_pooled_hidden_size,",
"1 if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round =",
"# Note that it will include the loss (tracked in",
"hidden_feature else: multiplier_name = '%s_loss_multiplier' % problem record_ind = tf.where(tf.cast(",
"activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None @tf.function def get_features_for_problem(self, features, hidden_feature,",
"problem_dict: problem_type = self.params.problem_type[problem] # some layers has different signatures,",
"self.params.custom_pooled_hidden_size, activation=tf.keras.activations.selu) else: self.custom_pooled_layer = None @tf.function def get_features_for_problem(self, features,",
"This method can be overridden to support custom evaluation logic.",
"logic. This method is called by `Model.make_test_function`. This function should",
"# tensor, [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_sequence_output() elif logit_type",
"for problem in problem_dict: problem_type = self.params.problem_type[problem] # some layers",
"self.metrics} # Compute gradients trainable_vars = self.trainable_variables gradients = tape.gradient(self.losses,",
"feature_per_problem, hidden_feature_per_problem = self.body( inputs, mode) pred_per_problem = self.top( (feature_per_problem,",
"m_list) return {m.name: m.result() for m in self.metrics} def predict_step(self,",
"tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean) with tf.compat.v1.name_scope('stddev'): stddev =",
"continue if 'acc' in metric.name: m_list.append(metric.result()) if 'f1' in metric.name:",
"= 0.0 else: return_loss = loss return return_loss class BertMultiTaskBody(tf.keras.Model):",
"features: feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind) return feature_this_round, hidden_feature_this_round def",
"self.bert.get_embedding_output() elif logit_type == 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() # for",
"features, hidden_feature if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer",
"tf.compat.v1.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean( input_tensor=tf.square(var - mean))) tf.compat.v1.summary.scalar('stddev', stddev) tf.compat.v1.summary.scalar('max',",
"record_ind, axis=0 ), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name]",
"except ValueError: # pass return return_dict # Cell class BertMultiTask(tf.keras.Model):",
"== 'pretrain': pretrain = self.top_layer_dict[problem] return_dict[problem] = pretrain( (feature_this_round, hidden_feature_this_round),",
"{} for features_name in features: feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind)",
"mode) else: feature_this_round, hidden_feature_this_round = features, hidden_feature if self.params.label_transfer and",
"for problem_dict in self.params.run_problem_list: for problem in problem_dict: feature_this_round =",
"= self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings)",
"hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type == 'embed': # for",
"# Update weights self.optimizer.apply_gradients(zip(gradients, trainable_vars)) self.mean_acc.update_state( [v for n, v",
"== 1 if mode == tf.estimator.ModeKeys.PREDICT: feature_this_round = features hidden_feature_this_round",
"dict mapping metric names to current value. # Note that",
"hidden_feature_this_round = self.get_features_for_problem( features, hidden_feature, problem, mode) else: feature_this_round, hidden_feature_this_round",
"from typing import Dict, Tuple from inspect import signature import",
"== 'embed': # for res connection hidden_feature[logit_type] = self.bert.get_embedding_output() elif",
"{} for problem_dict in self.params.run_problem_list: for problem in problem_dict: problem_type",
"elif logit_type == 'embed': # for res connection hidden_feature[logit_type] =",
"'acc' in metric.name: m_list.append(metric.result()) if 'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state(",
"to save computation for downstream processing. # For example, we",
"'BertMultiTask'] # Cell from typing import Dict, Tuple from inspect",
"tf.Tensor = None): super(BertMultiTaskTop, self).__init__(name=name) self.params = params problem_type_layer =",
"'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] Output: { 'a': {'input_ids': [1,2,3], 'a_loss_multiplier':",
"self.params = params self.bert = MultiModalBertModel(params=self.params) if self.params.custom_pooled_hidden_size: self.custom_pooled_layer =",
"), axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round =",
"= tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with tf.GradientTape() as tape: #",
"top_layer in self.top.top_layer_dict.items()} metric_dict = {m.name: m.result() for m in",
"} problem_type_layer.update(self.params.top_layer) self.top_layer_dict = {} for problem_dict in self.params.run_problem_list: for",
"get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top =",
"\"\"\"Model to create top layer, aka classification layer, for each",
"def call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]], mode:",
"Note that it will include the loss (tracked in self.metrics).",
"= get_embedding_table_from_model(self.body.bert.bert_model) main_model = get_transformer_main_model(self.body.bert.bert_model) # input_embeddings = self.body.bert.bert_model.bert.embeddings input_embeddings",
"def variable_summaries(var, name): \"\"\"Attach a lot of summaries to a",
") if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] =",
"def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem = self.body( inputs, mode)",
"'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6],",
"NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round return_feature[problem] = feature_this_round return return_feature, return_hidden_feature",
"= pretrain( (feature_this_round, hidden_feature_this_round), mode) return return_dict if self.params.label_transfer and",
"Dict, Tuple from inspect import signature import tensorflow as tf",
"\\ # mask_lm_top(features, # hidden_feature, mode, 'dummy') # except ValueError:",
"if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer and grid",
"problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str,",
"# For example, we have a batch of two instances",
"'seq_tag': SequenceLabel, 'cls': Classification, 'seq2seq_tag': Seq2Seq, 'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification,",
"BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN): feature_per_problem, hidden_feature_per_problem =",
"custom evaluation logic. This method is called by `Model.make_test_function`. This",
"[1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} # 'b': {'input_ids': [4,5,6], 'a_loss_multiplier':",
"the values of the `Model`'s metrics are returned. \"\"\" y_pred",
"if 'mean_acc' in metric.name: continue if 'acc' in metric.name: m_list.append(metric.result())",
"loss calculation, and metrics updates. Configuration details for *how* this",
"features for that problem. The reason behind this # is",
"num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def train_step(self, data): with",
"if 'f1' in metric.name: m_list.append(metric.result()) self.mean_acc.update_state( m_list) return {m.name: m.result()",
"DO NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified).",
"import Dict, Tuple from inspect import signature import tensorflow as",
"import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM) from .utils import",
"and `tf.distribute.Strategy` settings), should be left to `Model.make_test_function`, which can",
"metrics to calculate mean m_list = [] for metric in",
"# some layers has different signatures, assign inputs accordingly layer_signature_name",
"to a Tensor (for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean =",
"the mathemetical logic for one step of evaluation. This typically",
"self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm and",
"'a_loss_multiplier': 0, 'b_loss_multiplier': 1}] # Output: # { # 'a':",
"# extract bert hidden features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids'] =",
"'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} # } features",
"problem in problem_dict: if self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem] raise",
"\"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody, self).__init__(name=name) self.params =",
") with tf.name_scope(problem): layer = self.top_layer_dict[problem] return_dict[problem] = layer( (feature_this_round,",
"(for TensorBoard visualization).\"\"\" with tf.compat.v1.name_scope(name): mean = tf.reduce_mean(input_tensor=var) tf.compat.v1.summary.scalar('mean', mean)",
"passed to `tf.keras.callbacks.CallbackList.on_train_batch_end`. Typically, the values of the `Model`'s metrics",
"same time.' ) if self.params.grid_transformer: raise NotImplementedError return_hidden_feature[problem] = hidden_feature_this_round",
"NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless otherwise specified). __all__",
"features and hidden features for that problem. The reason behind",
"{signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def call(self, inputs: Tuple[Dict[str,",
"num_hidden_layers * [batch_size, seq_length, hidden_size] hidden_feature[logit_type] = self.bert.get_all_encoder_layers() elif logit_type",
"return_feature = {} return_hidden_feature = {} for problem_dict in self.params.run_problem_list:",
"logit_type == 'embed': # for res connection hidden_feature[logit_type] = self.bert.get_embedding_output()",
"current value. # Note that it will include the loss",
"structure of `Tensor`s. Returns: A `dict` containing values that will",
"hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type == 'all': # list,",
"return return_dict def test_step(self, data): \"\"\"The logic for one evaluation",
"# initialize body model, aka transformers self.body = BertMultiTaskBody(params=self.params) #",
"elif logit_type == 'embed_table': hidden_feature[logit_type] = self.bert.get_embedding_table() # for each",
"features, hidden_feature, problem, mode): # get features with ind ==",
"tf.Tensor]]], mode: str) -> Dict[str, tf.Tensor]: features, hidden_feature = inputs",
"metrics are returned. \"\"\" y_pred = self(data, mode=tf.estimator.ModeKeys.EVAL) # Updates",
"filter_loss(loss, features, problem): if tf.reduce_mean(input_tensor=features['%s_loss_multiplier' % problem]) == 0: return_loss",
"main_model.embeddings self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def call(self, inputs, mode=tf.estimator.ModeKeys.TRAIN):",
"[1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0} 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0,",
"= self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type",
"evaluation step. This method can be overridden to support custom",
"\"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskTop', input_embeddings: tf.Tensor = None):",
"self.body.bert.bert_model.bert.embeddings input_embeddings = main_model.embeddings self.top = BertMultiTaskTop( params=self.params, input_embeddings=input_embeddings) def",
"top_layer in self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics) for problem_name,",
"mapping metric names to current value. # Note that it",
"'b_loss_multiplier': 1} } \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskBody'): super(BertMultiTaskBody,",
"class BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams, name='BertMultiTask') -> None: super(BertMultiTask,",
"self.lr_scheduler = transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc =",
"`Tensor`s. Returns: A `dict` containing values that will be passed",
"raise NotImplementedError # try: # mask_lm_top = MaskLM(self.params) # return_dict['augument_mask_lm']",
"hidden_feature_name in hidden_feature: if hidden_feature_name != 'embed_table': hidden_feature_this_round[hidden_feature_name] = tf.squeeze(tf.gather(",
"updates. Configuration details for *how* this logic is run (e.g.",
"self.params.run_problem_list: for problem in problem_dict: problem_type = self.params.problem_type[problem] # some",
"BaseParams from .top import (Classification, MultiLabelClassification, PreTrain, Seq2Seq, SequenceLabel, MaskLM)",
"= features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type = self.params.problem_type[problem] # if",
"for problem in problem_dict: if self.params.task_transformer: # hidden_feature = task_tranformer_hidden_feature[problem]",
"# return_dict['augument_mask_lm'] = \\ # mask_lm_top(features, # hidden_feature, mode, 'dummy')",
"0: return_loss = 0.0 else: return_loss = loss return return_loss",
"= {'{}_loss'.format(problem_name): tf.reduce_sum(top_layer.losses) for problem_name, top_layer in self.top.top_layer_dict.items()} # metric_dict",
"return_dict def test_step(self, data): \"\"\"The logic for one evaluation step.",
"0} # 'b': {'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} #",
"= [] for metric in self.metrics: if 'mean_acc' in metric.name:",
"axis=1) hidden_feature_this_round[hidden_feature_name].set_shape( hidden_feature[hidden_feature_name].shape.as_list()) else: hidden_feature_this_round[hidden_feature_name] = hidden_feature[hidden_feature_name] feature_this_round = {}",
"metrics updates. Configuration details for *how* this logic is run",
"self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer and grid transformer",
"**inputs_kwargs) def call(self, inputs: Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]],",
"= signature( problem_type_layer[problem_type].__init__).parameters.keys() inputs_kwargs = { 'params': self.params, 'problem_name': problem",
"transformers.optimization_tf.create_optimizer( init_lr=self.params.lr, num_train_steps=self.params.train_steps, num_warmup_steps=self.params.num_warmup_steps, weight_decay_rate=0.01 ) self.mean_acc = tf.keras.metrics.Mean(name='mean_acc') def",
"for problem_name, top_layer in self.top.top_layer_dict.items()} # metric_dict = {'{}_metric'.format(problem_name): tf.reduce_mean(top_layer.metrics)",
"{'input_ids': [4,5,6], 'a_loss_multiplier': 0, 'b_loss_multiplier': 1} # } features =",
"return_dict[problem] = layer( (feature_this_round, hidden_feature_this_round), mode) if self.params.augument_mask_lm and mode",
"support custom evaluation logic. This method is called by `Model.make_test_function`.",
"evaluation. This typically includes the forward pass, loss calculation, and",
"has different signatures, assign inputs accordingly layer_signature_name = signature( problem_type_layer[problem_type].__init__).parameters.keys()",
"if 'acc' in metric.name: m_list.append(metric.result()) if 'f1' in metric.name: m_list.append(metric.result())",
"hidden features for that problem. The reason behind this is",
"= ['variable_summaries', 'filter_loss', 'BertMultiTaskBody', 'BertMultiTaskTop', 'BertMultiTask'] # Cell from typing",
"data): \"\"\"The logic for one evaluation step. This method can",
"= hidden_feature[hidden_feature_name] feature_this_round = {} for features_name in features: feature_this_round[features_name]",
"self.bert(inputs, mode == tf.estimator.ModeKeys.TRAIN) # extract bert hidden features inputs['model_input_mask']",
"signature_name == 'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs)",
"tf.estimator.ModeKeys.TRAIN) # extract bert hidden features inputs['model_input_mask'] = self.bert.get_input_mask() inputs['model_token_type_ids']",
"called by `Model.make_test_function`. This function should contain the mathemetical logic",
"grid transformer cannot be enabled in the same time.' )",
"cannot be enabled in the same time.' ) if self.params.grid_transformer:",
"'a_loss_multiplier': 0, 'b_loss_multiplier': 1} # } features = inputs return_feature",
"mode == tf.estimator.ModeKeys.TRAIN: raise NotImplementedError # try: # mask_lm_top =",
"self.custom_pooled_layer: hidden_feature[logit_type] = self.custom_pooled_layer( hidden_feature[logit_type]) elif logit_type == 'all': #",
"-> Dict[str, tf.Tensor]: features, hidden_feature = inputs return_dict = {}",
"0, 'b_loss_multiplier': 1} } \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskBody'):",
"return return_dict # Cell class BertMultiTask(tf.keras.Model): def __init__(self, params: BaseParams,",
"layer, for each problem. \"\"\" def __init__(self, params: BaseParams, name='BertMultiTaskTop',",
"have a batch of two instances and they're from #",
"return_dict if self.params.label_transfer and self.params.grid_transformer: raise ValueError( 'Label Transfer and",
"# Input: # [{'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier': 0}, #",
"tensor, [batch_size, hidden_size] hidden_feature[logit_type] = self.bert.get_pooled_output() if self.custom_pooled_layer: hidden_feature[logit_type] =",
"'input_embeddings': inputs_kwargs.update( {signature_name: input_embeddings}) self.top_layer_dict[problem] = problem_type_layer[problem_type]( **inputs_kwargs) def call(self,",
"transformer cannot be enabled in the same time.' ) with",
"mode: str) -> Tuple[Dict[str, Dict[str, tf.Tensor]], Dict[str, Dict[str, tf.Tensor]]]: _",
"self).compile() logger = tf.get_logger() logger.info('Initial lr: {}'.format(self.params.lr)) logger.info('Train steps: {}'.format(self.params.train_steps))",
"logic is run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be",
"pass _ = self(data, mode=tf.estimator.ModeKeys.TRAIN) # gather losses from all",
"= None @tf.function def get_features_for_problem(self, features, hidden_feature, problem, mode): #",
"Output: # { # 'a': {'input_ids': [1,2,3], 'a_loss_multiplier': 1, 'b_loss_multiplier':",
"feature_this_round = features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type = self.params.problem_type[problem] #",
"for problem_dict in self.params.run_problem_list: for problem in problem_dict: problem_type =",
"we extract corresponding features and hidden features for that problem.",
"problem in problem_dict: problem_type = self.params.problem_type[problem] # some layers has",
"run (e.g. `tf.function` and `tf.distribute.Strategy` settings), should be left to",
"'seq2seq_text': Seq2Seq, 'multi_cls': MultiLabelClassification, 'pretrain': PreTrain, 'masklm': MaskLM } problem_type_layer.update(self.params.top_layer)",
"in problem_dict: feature_this_round = features[problem] hidden_feature_this_round = hidden_feature[problem] problem_type =",
"hidden_feature = task_tranformer_hidden_feature[problem] raise NotImplementedError if len(self.params.run_problem_list) > 1: feature_this_round,",
"feature_this_round[features_name] = tf.gather_nd( features[features_name], record_ind) return feature_this_round, hidden_feature_this_round def call(self,",
"0, 'b_loss_multiplier': 1}] # Output: # { # 'a': {'input_ids':",
"# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/13_model_fn.ipynb (unless"
] |
[
"matplotlib.ticker import MaxNLocator import time class VisualizationCallback(Callback): def __init__(self, **kwargs)",
"np.array([]) for i, sim_name in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id",
"not square, find divisible number to get rectangle else: number",
"self.kwargs['plot_dir'] else: plot_dir = os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn",
"0.5) ** 2 == num_sim: number = int(math.sqrt(num_sim)) y_num =",
"showing the progress of the simulations :param num_sim: number of",
"from SiMon.simulation import Simulation from SiMon.callback import Callback from matplotlib.ticker",
"np.array([]) sim_idx = np.array([]) for i, sim_name in enumerate(sim_inst_dict): sim",
"only a place holder # only plot level=1 simulations if",
"X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to",
"__init__(self, **kwargs) -> None: super().__init__(**kwargs) def run(self): self.plot_progress() def plot_progress(self):",
"sim_idx // number plt.figure(1, figsize=(12, 12)) ax = plt.gca() #",
"i).sum() == 0: continue else: plt.scatter( x_sim[status == i], y_sim[status",
"sim_inst_dict[sim_name] sim_id = sim.id if sim_id == 0: continue #",
"num_sim: y_num = y_num - 1 x_sim = sim_idx %",
"= datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs: fmt = self.kwargs['format'] else:",
"= num_sim // number # If not square, find divisible",
"the axis ax.xaxis.tick_top() # and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num))",
"* number) > num_sim and ((y_num - 1) * number)",
"i, sim_name in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id = sim.id",
"new name # if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: #",
"= y_num - 1 x_sim = sim_idx % number y_sim",
"self.kwargs: fmt = self.kwargs['format'] else: fmt = 'png' fullpath =",
"x_sim = sim_idx % number y_sim = sim_idx // number",
"# print('saving figure') if 'plot_dir' in self.kwargs: plot_dir = self.kwargs['plot_dir']",
"s = sim.sim_get_status() if sim.t_max > 0: p = sim.t",
"= sim.t / sim.t_max else: p = 0.0 status =",
"numpy as np import math from datetime import datetime from",
"# set to integers ax.yaxis.tick_left() # remove right y-Ticks symbols",
"os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs: fmt =",
"# and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks",
"number of simulations :return: \"\"\" if 'container' in self.kwargs: sim_inst_dict",
"bbox_to_anchor=(0., -.15, 1., .102), loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2,",
"'s', '>', '^', '*', 'x'] labels = ['NEW', 'STOP', 'RUN',",
"self.kwargs['format'] else: fmt = 'png' fullpath = os.path.join(plot_dir, '%s.%s' %",
"import cm from SiMon.simulation import Simulation from SiMon.callback import Callback",
"plot_progress(self): \"\"\" Creates a graph showing the progress of the",
"Simulation from SiMon.callback import Callback from matplotlib.ticker import MaxNLocator import",
"graph fits all num_sim y_num = number # 'Removes' extra",
"fmt = self.kwargs['format'] else: fmt = 'png' fullpath = os.path.join(plot_dir,",
"# Make sure graph fits all num_sim y_num = number",
"'%s.%s' % (fn, fmt)) print('Progress plot saved on %s' %",
"a square if int(math.sqrt(num_sim) + 0.5) ** 2 == num_sim:",
"= plt.gca() # get the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the",
"os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy",
"'DONE', 'ERROR'] for i, symbol in enumerate(symbols): if (status ==",
"-> None: super().__init__(**kwargs) def run(self): self.plot_progress() def plot_progress(self): \"\"\" Creates",
"cmap=cm.RdYlBu, vmin = 0., vmax = 1., label=labels[i]) for i",
"for i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold',",
"if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in",
"number # If not square, find divisible number to get",
"sim.id if sim_id == 0: continue # skip the root",
"= sim_idx % number y_sim = sim_idx // number plt.figure(1,",
"import datetime from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections import",
"# 'Removes' extra white line if graph is too big",
"move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) #",
"== i], marker=symbol, s=500, c=progresses[status == i], cmap=cm.RdYlBu, vmin =",
"import math from datetime import datetime from matplotlib.colors import ListedColormap,",
"figure') if 'plot_dir' in self.kwargs: plot_dir = self.kwargs['plot_dir'] else: plot_dir",
"ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers",
"+ 0.5) ** 2 == num_sim: number = int(math.sqrt(num_sim)) y_num",
"if 'container' in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return num_sim",
"number - 1 y_num = num_sim // number # Y-axis",
"simulations :param num_sim: number of simulations :return: \"\"\" if 'container'",
"symbol in enumerate(symbols): if (status == i).sum() == 0: continue",
"'plot_dir' in self.kwargs: plot_dir = self.kwargs['plot_dir'] else: plot_dir = os.getcwd()",
"skip the root simulation instance, which is only a place",
"'^', '*', 'x'] labels = ['NEW', 'STOP', 'RUN', 'STALL', 'DONE',",
"number) > num_sim and ((y_num - 1) * number) >=",
"only plot level=1 simulations if sim.level > 1: continue s",
"i], cmap=cm.RdYlBu, vmin = 0., vmax = 1., label=labels[i]) for",
"p = sim.t / sim.t_max else: p = 0.0 status",
"as plt import numpy as np import math from datetime",
"== 0: continue # skip the root simulation instance, which",
"if sim.level > 1: continue s = sim.sim_get_status() if sim.t_max",
"Save file with a new name # if os.path.exists('progress.pdf'): #",
"'STALL', 'DONE', 'ERROR'] for i, symbol in enumerate(symbols): if (status",
"def plot_progress(self): \"\"\" Creates a graph showing the progress of",
"size=15 ) plt.legend( bbox_to_anchor=(0., -.15, 1., .102), loc='lower center', ncol=4,",
"label=labels[i]) for i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black',",
"big if (y_num * number) > num_sim and ((y_num -",
"np import math from datetime import datetime from matplotlib.colors import",
"matplotlib.collections import LineCollection from matplotlib import cm from SiMon.simulation import",
"'RUN', 'STALL', 'DONE', 'ERROR'] for i, symbol in enumerate(symbols): if",
"get rectangle else: number = int(math.sqrt(num_sim)) while num_sim % number",
"int(math.sqrt(num_sim)) y_num = num_sim // number # If not square,",
"white line if graph is too big if (y_num *",
"number) >= num_sim: y_num = y_num - 1 x_sim =",
"def run(self): self.plot_progress() def plot_progress(self): \"\"\" Creates a graph showing",
"int(math.sqrt(num_sim) + 0.5) ** 2 == num_sim: number = int(math.sqrt(num_sim))",
"number y_sim = sim_idx // number plt.figure(1, figsize=(12, 12)) ax",
"== i).sum() == 0: continue else: plt.scatter( x_sim[status == i],",
"sim_idx % number y_sim = sim_idx // number plt.figure(1, figsize=(12,",
"= ['o', 's', '>', '^', '*', 'x'] labels = ['NEW',",
"borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar() # # Save file with",
"holder # only plot level=1 simulations if sim.level > 1:",
"['o', 's', '>', '^', '*', 'x'] labels = ['NEW', 'STOP',",
"a graph showing the progress of the simulations :param num_sim:",
"sim_id == 0: continue # skip the root simulation instance,",
"== 0: continue else: plt.scatter( x_sim[status == i], y_sim[status ==",
"plt.colorbar() # # Save file with a new name #",
"def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def run(self): self.plot_progress() def",
"# get the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis ax.xaxis.tick_top()",
"** 2 == num_sim: number = int(math.sqrt(num_sim)) y_num = num_sim",
"divisible number to get rectangle else: number = int(math.sqrt(num_sim)) while",
"np.array([]) progresses = np.array([]) sim_idx = np.array([]) for i, sim_name",
"y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers ax.yaxis.tick_left() # remove right",
"- 1 x_sim = sim_idx % number y_sim = sim_idx",
"Checks if num_sim has a square if int(math.sqrt(num_sim) + 0.5)",
"if 'plot_dir' in self.kwargs: plot_dir = self.kwargs['plot_dir'] else: plot_dir =",
"from matplotlib.ticker import MaxNLocator import time class VisualizationCallback(Callback): def __init__(self,",
"plot_dir = self.kwargs['plot_dir'] else: plot_dir = os.getcwd() if not os.path.isdir(plot_dir):",
"else: p = 0.0 status = np.append(s, status) progresses =",
"num_sim: number = int(math.sqrt(num_sim)) y_num = num_sim // number #",
"self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return num_sim = len(sim_inst_dict) status",
"too big if (y_num * number) > num_sim and ((y_num",
"matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection from matplotlib",
"BoundaryNorm from matplotlib.collections import LineCollection from matplotlib import cm from",
"labelspacing=3 ) plt.colorbar() # # Save file with a new",
"time class VisualizationCallback(Callback): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def",
"num_sim y_num = number # 'Removes' extra white line if",
"= os.path.join(plot_dir, '%s.%s' % (fn, fmt)) print('Progress plot saved on",
"import Callback from matplotlib.ticker import MaxNLocator import time class VisualizationCallback(Callback):",
"'*', 'x'] labels = ['NEW', 'STOP', 'RUN', 'STALL', 'DONE', 'ERROR']",
"number = int(math.sqrt(num_sim)) + 1 # Make sure graph fits",
"0: number = number - 1 y_num = num_sim //",
"while num_sim % number != 0: number = number -",
"y_num = number # 'Removes' extra white line if graph",
"y_num - 1 x_sim = sim_idx % number y_sim =",
"= sim.sim_get_status() if sim.t_max > 0: p = sim.t /",
"for i, sim_name in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id =",
"super().__init__(**kwargs) def run(self): self.plot_progress() def plot_progress(self): \"\"\" Creates a graph",
"datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs: fmt = self.kwargs['format'] else: fmt",
"y_sim[status == i], marker=symbol, s=500, c=progresses[status == i], cmap=cm.RdYlBu, vmin",
"= num_sim // number # Y-axis limit # If prime",
"Make sure graph fits all num_sim y_num = number #",
"sim_name in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id = sim.id if",
"fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs: fmt = self.kwargs['format']",
"continue # skip the root simulation instance, which is only",
"matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import",
"s=500, c=progresses[status == i], cmap=cm.RdYlBu, vmin = 0., vmax =",
"# plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving figure') if 'plot_dir' in",
"# If prime number if number == 1: number =",
"+ 1 # Make sure graph fits all num_sim y_num",
"['NEW', 'STOP', 'RUN', 'STALL', 'DONE', 'ERROR'] for i, symbol in",
"np.append(sim_id, sim_idx) # Checks if num_sim has a square if",
"math from datetime import datetime from matplotlib.colors import ListedColormap, BoundaryNorm",
"square if int(math.sqrt(num_sim) + 0.5) ** 2 == num_sim: number",
"if num_sim has a square if int(math.sqrt(num_sim) + 0.5) **",
"1., .102), loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 )",
"in self.kwargs: fmt = self.kwargs['format'] else: fmt = 'png' fullpath",
"fits all num_sim y_num = number # 'Removes' extra white",
"plot_dir = os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\")",
"% number != 0: number = number - 1 y_num",
"is too big if (y_num * number) > num_sim and",
"num_sim % number != 0: number = number - 1",
"labels = ['NEW', 'STOP', 'RUN', 'STALL', 'DONE', 'ERROR'] for i,",
"VisualizationCallback(Callback): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def run(self): self.plot_progress()",
"import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import",
"else: plot_dir = os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn =",
"continue else: plt.scatter( x_sim[status == i], y_sim[status == i], marker=symbol,",
"LineCollection from matplotlib import cm from SiMon.simulation import Simulation from",
"- 1 y_num = num_sim // number # Y-axis limit",
"continue s = sim.sim_get_status() if sim.t_max > 0: p =",
"else: fmt = 'png' fullpath = os.path.join(plot_dir, '%s.%s' % (fn,",
"# Save file with a new name # if os.path.exists('progress.pdf'):",
"number # Y-axis limit # If prime number if number",
"y_num = num_sim // number # If not square, find",
"num_sim // number # If not square, find divisible number",
"from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection from",
"# invert the axis ax.xaxis.tick_top() # and move the X-Axis",
"0: p = sim.t / sim.t_max else: p = 0.0",
"1) * number) >= num_sim: y_num = y_num - 1",
"else: # print('saving figure') if 'plot_dir' in self.kwargs: plot_dir =",
"'format' in self.kwargs: fmt = self.kwargs['format'] else: fmt = 'png'",
"matplotlib.pyplot as plt import numpy as np import math from",
"plt.figure(1, figsize=(12, 12)) ax = plt.gca() # get the axis",
"(y_num * number) > num_sim and ((y_num - 1) *",
"= 1., label=labels[i]) for i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i],",
"'Removes' extra white line if graph is too big if",
"prime number if number == 1: number = int(math.sqrt(num_sim)) +",
"the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set",
"Creates a graph showing the progress of the simulations :param",
"sim = sim_inst_dict[sim_name] sim_id = sim.id if sim_id == 0:",
"borderpad=2, labelspacing=3 ) plt.colorbar() # # Save file with a",
") plt.colorbar() # # Save file with a new name",
"run(self): self.plot_progress() def plot_progress(self): \"\"\" Creates a graph showing the",
"1: continue s = sim.sim_get_status() if sim.t_max > 0: p",
"all num_sim y_num = number # 'Removes' extra white line",
"= sim_idx // number plt.figure(1, figsize=(12, 12)) ax = plt.gca()",
"int(math.sqrt(num_sim)) + 1 # Make sure graph fits all num_sim",
"remove right y-Ticks symbols = ['o', 's', '>', '^', '*',",
"x_sim[status == i], y_sim[status == i], marker=symbol, s=500, c=progresses[status ==",
"simulations if sim.level > 1: continue s = sim.sim_get_status() if",
"if graph is too big if (y_num * number) >",
"status = np.array([]) progresses = np.array([]) sim_idx = np.array([]) for",
"for i, symbol in enumerate(symbols): if (status == i).sum() ==",
"# set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers ax.yaxis.tick_left() #",
"MaxNLocator import time class VisualizationCallback(Callback): def __init__(self, **kwargs) -> None:",
"'ERROR'] for i, symbol in enumerate(symbols): if (status == i).sum()",
"os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format'",
"os.path.join(plot_dir, '%s.%s' % (fn, fmt)) print('Progress plot saved on %s'",
"number to get rectangle else: number = int(math.sqrt(num_sim)) while num_sim",
"i], marker=symbol, s=500, c=progresses[status == i], cmap=cm.RdYlBu, vmin = 0.,",
"- 1) * number) >= num_sim: y_num = y_num -",
"0.0 status = np.append(s, status) progresses = np.append(p, progresses) sim_idx",
"# Checks if num_sim has a square if int(math.sqrt(num_sim) +",
"import matplotlib.pyplot as plt import numpy as np import math",
"progresses = np.array([]) sim_idx = np.array([]) for i, sim_name in",
"import numpy as np import math from datetime import datetime",
"status = np.append(s, status) progresses = np.append(p, progresses) sim_idx =",
"marker=symbol, s=500, c=progresses[status == i], cmap=cm.RdYlBu, vmin = 0., vmax",
"y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers ax.yaxis.tick_left()",
"import LineCollection from matplotlib import cm from SiMon.simulation import Simulation",
"a new name # if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else:",
"with a new name # if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) #",
"the progress of the simulations :param num_sim: number of simulations",
"place holder # only plot level=1 simulations if sim.level >",
"import Simulation from SiMon.callback import Callback from matplotlib.ticker import MaxNLocator",
"# # Save file with a new name # if",
"return num_sim = len(sim_inst_dict) status = np.array([]) progresses = np.array([])",
"= number - 1 y_num = num_sim // number #",
"sim.t_max else: p = 0.0 status = np.append(s, status) progresses",
"If not square, find divisible number to get rectangle else:",
"datetime from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection",
"= np.array([]) for i, sim_name in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name]",
"text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0., -.15,",
"symbols = ['o', 's', '>', '^', '*', 'x'] labels =",
"matplotlib import cm from SiMon.simulation import Simulation from SiMon.callback import",
"# remove right y-Ticks symbols = ['o', 's', '>', '^',",
"number = int(math.sqrt(num_sim)) while num_sim % number != 0: number",
"== i], y_sim[status == i], marker=symbol, s=500, c=progresses[status == i],",
"plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving figure') if 'plot_dir' in self.kwargs:",
"fmt)) print('Progress plot saved on %s' % fullpath) plt.savefig(fullpath) plt.close(1)",
".102), loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar()",
"// number # Y-axis limit # If prime number if",
"as np import math from datetime import datetime from matplotlib.colors",
"from matplotlib import cm from SiMon.simulation import Simulation from SiMon.callback",
"import time class VisualizationCallback(Callback): def __init__(self, **kwargs) -> None: super().__init__(**kwargs)",
"= int(math.sqrt(num_sim)) + 1 # Make sure graph fits all",
"import ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection from matplotlib import",
"int(math.sqrt(num_sim)) while num_sim % number != 0: number = number",
"= np.append(sim_id, sim_idx) # Checks if num_sim has a square",
"if 'format' in self.kwargs: fmt = self.kwargs['format'] else: fmt =",
"'png' fullpath = os.path.join(plot_dir, '%s.%s' % (fn, fmt)) print('Progress plot",
"== num_sim: number = int(math.sqrt(num_sim)) y_num = num_sim // number",
"simulations :return: \"\"\" if 'container' in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict",
"plt.scatter( x_sim[status == i], y_sim[status == i], marker=symbol, s=500, c=progresses[status",
"number plt.figure(1, figsize=(12, 12)) ax = plt.gca() # get the",
"num_sim // number # Y-axis limit # If prime number",
"-.15, 1., .102), loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3",
"figsize=(12, 12)) ax = plt.gca() # get the axis ax.set_ylim(ax.get_ylim()[::-1])",
"!= 0: number = number - 1 y_num = num_sim",
"= 'png' fullpath = os.path.join(plot_dir, '%s.%s' % (fn, fmt)) print('Progress",
"enumerate(symbols): if (status == i).sum() == 0: continue else: plt.scatter(",
"# If not square, find divisible number to get rectangle",
"number if number == 1: number = int(math.sqrt(num_sim)) + 1",
"if (status == i).sum() == 0: continue else: plt.scatter( x_sim[status",
"sim.t_max > 0: p = sim.t / sim.t_max else: p",
"sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return num_sim = len(sim_inst_dict) status =",
"set to integers ax.yaxis.tick_left() # remove right y-Ticks symbols =",
"= self.kwargs['plot_dir'] else: plot_dir = os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir)",
"= len(sim_inst_dict) status = np.array([]) progresses = np.array([]) sim_idx =",
"sim_idx) # Checks if num_sim has a square if int(math.sqrt(num_sim)",
"instance, which is only a place holder # only plot",
"number == 1: number = int(math.sqrt(num_sim)) + 1 # Make",
"c=progresses[status == i], cmap=cm.RdYlBu, vmin = 0., vmax = 1.,",
"i, symbol in enumerate(symbols): if (status == i).sum() == 0:",
"from matplotlib.collections import LineCollection from matplotlib import cm from SiMon.simulation",
"in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15 )",
"from SiMon.callback import Callback from matplotlib.ticker import MaxNLocator import time",
"\"\"\" if 'container' in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return",
"and ((y_num - 1) * number) >= num_sim: y_num =",
"to integers ax.yaxis.tick_left() # remove right y-Ticks symbols = ['o',",
"(status == i).sum() == 0: continue else: plt.scatter( x_sim[status ==",
"= sim_inst_dict[sim_name] sim_id = sim.id if sim_id == 0: continue",
"'STOP', 'RUN', 'STALL', 'DONE', 'ERROR'] for i, symbol in enumerate(symbols):",
"y_sim[i]), color='black', weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0., -.15, 1., .102),",
"integers ax.yaxis.tick_left() # remove right y-Ticks symbols = ['o', 's',",
"graph is too big if (y_num * number) > num_sim",
"sim_idx = np.append(sim_id, sim_idx) # Checks if num_sim has a",
"== i], cmap=cm.RdYlBu, vmin = 0., vmax = 1., label=labels[i])",
"matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np",
"If prime number if number == 1: number = int(math.sqrt(num_sim))",
"Callback from matplotlib.ticker import MaxNLocator import time class VisualizationCallback(Callback): def",
"else: number = int(math.sqrt(num_sim)) while num_sim % number != 0:",
"* number) >= num_sim: y_num = y_num - 1 x_sim",
"# else: # print('saving figure') if 'plot_dir' in self.kwargs: plot_dir",
"= ['NEW', 'STOP', 'RUN', 'STALL', 'DONE', 'ERROR'] for i, symbol",
"plt import numpy as np import math from datetime import",
"len(sim_inst_dict) status = np.array([]) progresses = np.array([]) sim_idx = np.array([])",
"if int(math.sqrt(num_sim) + 0.5) ** 2 == num_sim: number =",
"if number == 1: number = int(math.sqrt(num_sim)) + 1 #",
"else: plt.scatter( x_sim[status == i], y_sim[status == i], marker=symbol, s=500,",
"color='black', weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0., -.15, 1., .102), loc='lower",
"sim.level > 1: continue s = sim.sim_get_status() if sim.t_max >",
"if (y_num * number) > num_sim and ((y_num - 1)",
"Y-axis limit # If prime number if number == 1:",
"invert the axis ax.xaxis.tick_top() # and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5,",
"y_sim = sim_idx // number plt.figure(1, figsize=(12, 12)) ax =",
"= os.getcwd() if not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if",
"in self.kwargs: plot_dir = self.kwargs['plot_dir'] else: plot_dir = os.getcwd() if",
"a place holder # only plot level=1 simulations if sim.level",
"1., label=labels[i]) for i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]),",
"the simulations :param num_sim: number of simulations :return: \"\"\" if",
"number = number - 1 y_num = num_sim // number",
"// number plt.figure(1, figsize=(12, 12)) ax = plt.gca() # get",
"ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar() # # Save",
"level=1 simulations if sim.level > 1: continue s = sim.sim_get_status()",
"self.kwargs['container'].sim_inst_dict else: return num_sim = len(sim_inst_dict) status = np.array([]) progresses",
"name # if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving",
"% (fn, fmt)) print('Progress plot saved on %s' % fullpath)",
"os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving figure') if 'plot_dir'",
"progresses) sim_idx = np.append(sim_id, sim_idx) # Checks if num_sim has",
"= int(math.sqrt(num_sim)) while num_sim % number != 0: number =",
"plot level=1 simulations if sim.level > 1: continue s =",
"np.append(p, progresses) sim_idx = np.append(sim_id, sim_idx) # Checks if num_sim",
":param num_sim: number of simulations :return: \"\"\" if 'container' in",
"SiMon.callback import Callback from matplotlib.ticker import MaxNLocator import time class",
"progresses = np.append(p, progresses) sim_idx = np.append(sim_id, sim_idx) # Checks",
"import MaxNLocator import time class VisualizationCallback(Callback): def __init__(self, **kwargs) ->",
"plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0.,",
"set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers ax.yaxis.tick_left() # remove",
"loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar() #",
"sim_id = sim.id if sim_id == 0: continue # skip",
"((y_num - 1) * number) >= num_sim: y_num = y_num",
"= self.kwargs['format'] else: fmt = 'png' fullpath = os.path.join(plot_dir, '%s.%s'",
"/ sim.t_max else: p = 0.0 status = np.append(s, status)",
"# only plot level=1 simulations if sim.level > 1: continue",
"progress of the simulations :param num_sim: number of simulations :return:",
") plt.legend( bbox_to_anchor=(0., -.15, 1., .102), loc='lower center', ncol=4, mode=\"expand\",",
"self.kwargs: plot_dir = self.kwargs['plot_dir'] else: plot_dir = os.getcwd() if not",
"cm from SiMon.simulation import Simulation from SiMon.callback import Callback from",
"if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving figure') if",
"ax = plt.gca() # get the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert",
"y_num = y_num - 1 x_sim = sim_idx % number",
"= self.kwargs['container'].sim_inst_dict else: return num_sim = len(sim_inst_dict) status = np.array([])",
"1 x_sim = sim_idx % number y_sim = sim_idx //",
"of the simulations :param num_sim: number of simulations :return: \"\"\"",
":return: \"\"\" if 'container' in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else:",
"np.append(s, status) progresses = np.append(p, progresses) sim_idx = np.append(sim_id, sim_idx)",
"y_num = num_sim // number # Y-axis limit # If",
"> 1: continue s = sim.sim_get_status() if sim.t_max > 0:",
"// number # If not square, find divisible number to",
"find divisible number to get rectangle else: number = int(math.sqrt(num_sim))",
"= np.array([]) sim_idx = np.array([]) for i, sim_name in enumerate(sim_inst_dict):",
"if sim_id == 0: continue # skip the root simulation",
"right y-Ticks symbols = ['o', 's', '>', '^', '*', 'x']",
"vmax = 1., label=labels[i]) for i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id),",
"# if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time()))) # else: # print('saving figure')",
"datetime import datetime from matplotlib.colors import ListedColormap, BoundaryNorm from matplotlib.collections",
"% number y_sim = sim_idx // number plt.figure(1, figsize=(12, 12))",
"is only a place holder # only plot level=1 simulations",
"axis ax.xaxis.tick_top() # and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) #",
"ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis ax.xaxis.tick_top() # and move the",
"get the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis ax.xaxis.tick_top() #",
"**kwargs) -> None: super().__init__(**kwargs) def run(self): self.plot_progress() def plot_progress(self): \"\"\"",
"in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return num_sim = len(sim_inst_dict)",
"enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id = sim.id if sim_id ==",
"num_sim has a square if int(math.sqrt(num_sim) + 0.5) ** 2",
"line if graph is too big if (y_num * number)",
"= number # 'Removes' extra white line if graph is",
"None: super().__init__(**kwargs) def run(self): self.plot_progress() def plot_progress(self): \"\"\" Creates a",
"'container' in self.kwargs: sim_inst_dict = self.kwargs['container'].sim_inst_dict else: return num_sim =",
"2 == num_sim: number = int(math.sqrt(num_sim)) y_num = num_sim //",
"and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set y-ticks ax.yaxis.set_major_locator(MaxNLocator(integer=True))",
"y-Ticks symbols = ['o', 's', '>', '^', '*', 'x'] labels",
"number != 0: number = number - 1 y_num =",
"class VisualizationCallback(Callback): def __init__(self, **kwargs) -> None: super().__init__(**kwargs) def run(self):",
"12)) ax = plt.gca() # get the axis ax.set_ylim(ax.get_ylim()[::-1]) #",
"the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis ax.xaxis.tick_top() # and",
"root simulation instance, which is only a place holder #",
"in enumerate(sim_inst_dict): sim = sim_inst_dict[sim_name] sim_id = sim.id if sim_id",
"sim_idx = np.array([]) for i, sim_name in enumerate(sim_inst_dict): sim =",
"'>', '^', '*', 'x'] labels = ['NEW', 'STOP', 'RUN', 'STALL',",
"ax.yaxis.set_major_locator(MaxNLocator(integer=True)) # set to integers ax.yaxis.tick_left() # remove right y-Ticks",
"os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs: fmt",
"which is only a place holder # only plot level=1",
">= num_sim: y_num = y_num - 1 x_sim = sim_idx",
"to get rectangle else: number = int(math.sqrt(num_sim)) while num_sim %",
"1 y_num = num_sim // number # Y-axis limit #",
"ListedColormap, BoundaryNorm from matplotlib.collections import LineCollection from matplotlib import cm",
"= sim.id if sim_id == 0: continue # skip the",
"status) progresses = np.append(p, progresses) sim_idx = np.append(sim_id, sim_idx) #",
"sim.t / sim.t_max else: p = 0.0 status = np.append(s,",
"self.plot_progress() def plot_progress(self): \"\"\" Creates a graph showing the progress",
"= np.append(p, progresses) sim_idx = np.append(sim_id, sim_idx) # Checks if",
"= 0.0 status = np.append(s, status) progresses = np.append(p, progresses)",
"= 0., vmax = 1., label=labels[i]) for i in range(sim_idx.shape[0]):",
"sim.sim_get_status() if sim.t_max > 0: p = sim.t / sim.t_max",
"rectangle else: number = int(math.sqrt(num_sim)) while num_sim % number !=",
"i in range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15",
"file with a new name # if os.path.exists('progress.pdf'): # plt.savefig('progress_{}.pdf'.format(int(time.time())))",
"vmin = 0., vmax = 1., label=labels[i]) for i in",
"mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar() # # Save file",
"= int(math.sqrt(num_sim)) y_num = num_sim // number # If not",
"# skip the root simulation instance, which is only a",
"1: number = int(math.sqrt(num_sim)) + 1 # Make sure graph",
"== 1: number = int(math.sqrt(num_sim)) + 1 # Make sure",
"in enumerate(symbols): if (status == i).sum() == 0: continue else:",
"else: return num_sim = len(sim_inst_dict) status = np.array([]) progresses =",
"p = 0.0 status = np.append(s, status) progresses = np.append(p,",
"number = int(math.sqrt(num_sim)) y_num = num_sim // number # If",
"the root simulation instance, which is only a place holder",
"xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0., -.15, 1.,",
"ax.yaxis.tick_left() # remove right y-Ticks symbols = ['o', 's', '>',",
"number # 'Removes' extra white line if graph is too",
"limit # If prime number if number == 1: number",
"weight='bold', size=15 ) plt.legend( bbox_to_anchor=(0., -.15, 1., .102), loc='lower center',",
"0: continue # skip the root simulation instance, which is",
"# Y-axis limit # If prime number if number ==",
"print('saving figure') if 'plot_dir' in self.kwargs: plot_dir = self.kwargs['plot_dir'] else:",
"fmt = 'png' fullpath = os.path.join(plot_dir, '%s.%s' % (fn, fmt))",
"axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis ax.xaxis.tick_top() # and move",
"not os.path.isdir(plot_dir): os.mkdir(plot_dir) fn = datetime.now().strftime(\"%d_%m_%Y-%H_%M_%S\") if 'format' in self.kwargs:",
"num_sim and ((y_num - 1) * number) >= num_sim: y_num",
"num_sim = len(sim_inst_dict) status = np.array([]) progresses = np.array([]) sim_idx",
"sure graph fits all num_sim y_num = number # 'Removes'",
"import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as",
"extra white line if graph is too big if (y_num",
"fullpath = os.path.join(plot_dir, '%s.%s' % (fn, fmt)) print('Progress plot saved",
"if sim.t_max > 0: p = sim.t / sim.t_max else:",
"0., vmax = 1., label=labels[i]) for i in range(sim_idx.shape[0]): plt.annotate(",
"= np.append(s, status) progresses = np.append(p, progresses) sim_idx = np.append(sim_id,",
"> 0: p = sim.t / sim.t_max else: p =",
"SiMon.simulation import Simulation from SiMon.callback import Callback from matplotlib.ticker import",
"range(sim_idx.shape[0]): plt.annotate( text=str(sim_inst_dict[i].id), xy=(x_sim[i], y_sim[i]), color='black', weight='bold', size=15 ) plt.legend(",
"<gh_stars>1-10 import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt",
"of simulations :return: \"\"\" if 'container' in self.kwargs: sim_inst_dict =",
"plt.legend( bbox_to_anchor=(0., -.15, 1., .102), loc='lower center', ncol=4, mode=\"expand\", borderaxespad=0.,",
"from datetime import datetime from matplotlib.colors import ListedColormap, BoundaryNorm from",
"= np.array([]) progresses = np.array([]) sim_idx = np.array([]) for i,",
"graph showing the progress of the simulations :param num_sim: number",
"square, find divisible number to get rectangle else: number =",
"\"\"\" Creates a graph showing the progress of the simulations",
"> num_sim and ((y_num - 1) * number) >= num_sim:",
"center', ncol=4, mode=\"expand\", borderaxespad=0., borderpad=2, labelspacing=3 ) plt.colorbar() # #",
"(fn, fmt)) print('Progress plot saved on %s' % fullpath) plt.savefig(fullpath)",
"has a square if int(math.sqrt(num_sim) + 0.5) ** 2 ==",
"simulation instance, which is only a place holder # only",
"ax.xaxis.tick_top() # and move the X-Axis ax.yaxis.set_ticks(np.arange(-0.5, y_num)) # set",
"'x'] labels = ['NEW', 'STOP', 'RUN', 'STALL', 'DONE', 'ERROR'] for",
"plt.gca() # get the axis ax.set_ylim(ax.get_ylim()[::-1]) # invert the axis",
"1 # Make sure graph fits all num_sim y_num =",
"0: continue else: plt.scatter( x_sim[status == i], y_sim[status == i],",
"i], y_sim[status == i], marker=symbol, s=500, c=progresses[status == i], cmap=cm.RdYlBu,",
"num_sim: number of simulations :return: \"\"\" if 'container' in self.kwargs:"
] |
[
"added in sufficient quantities, the interfacial # tension reduces and",
"size gets smaller. At a dispersant # to oil ratio",
"the properties of the jet object and # re-running the",
"34.5 rho = seawater.density(T, S, 101325.) P = 101325. +",
"median droplet size for the no-disperant experiment is:') print(' Measured:",
"They also used seawater (assumed salinity of 34.5 psu) and",
"jet object are currently correct. Hence, we may use: jet.simulate(d0,",
"to the measured data as follows: print('\\nThe median droplet size",
"University <<EMAIL>>. from __future__ import (absolute_import, division, print_function) from tamoc",
"about 6 m at a temperature of 13 deg C",
"a nozzle diameter of 1.5 mm d0 = 0.0015 #",
"= 101325. + rho * 9.81 * 6. rho =",
"mu, fp_type = 1) jet.simulate(d0, md_oil) # We compare the",
"of 50, sigma is: sigma = 0.05e-3 # We can",
"S, 101325.) P = 101325. + rho * 9.81 *",
"Use the ``TAMOC`` `particle_size_models` module to simulate a laboratory scale",
"oil. u_oil = 11.3 A_oil = np.pi * (d0 /",
"psu) and released the # oil from a depth of",
"velocity at the nozzle. We # need to convert this",
"jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1)",
"mass flow rate. The mass flow rate should # always",
"# We can also plot the size distribution print('\\nThe corresponding",
"Texas A&M University <<EMAIL>>. from __future__ import (absolute_import, division, print_function)",
"module to simulate a laboratory scale pure oil jet into",
"839.3 mu_oil = 5.e-3 sigma = 15.5e-3 # We will",
"seawater (assumed salinity of 34.5 psu) and released the #",
"__future__ import (absolute_import, division, print_function) from tamoc import seawater, particle_size_models",
"2.)**2 q_oil = u_oil * A_oil md_oil = np.array([rho_oil *",
"mu, fp_type = 1) # Brandvik et al. (2013) report",
"different pseudocomponents of the oil. u_oil = 11.3 A_oil =",
"properties rho_oil = 839.3 mu_oil = 5.e-3 sigma = 15.5e-3",
"The mass flow rate should # always be reported within",
"data uses # Oseberg oil, with the following reported properties",
"We compare the result to the measured data as follows:",
"import seawater, particle_size_models import numpy as np import warnings warnings.filterwarnings(\"ignore\")",
"dispersant # to oil ratio of 50, sigma is: sigma",
"tamoc import seawater, particle_size_models import numpy as np import warnings",
"print('Demonstration using the PureJet class in the') print('particle_size_models module of",
"experiments have a nozzle diameter of 1.5 mm d0 =",
"C T = 273.15 + 13. S = 34.5 rho",
"nozzle. We # need to convert this to a mass",
"fp_type = 1) jet.simulate(d0, md_oil) # We compare the result",
"TAMOC for the ') print('experiments in the paper by Brandvik",
"rate. The mass flow rate should # always be reported",
"no-disperant experiment is:') print(' Measured: %3.3d um' % 237) print('",
"Brandvik et al. (2013) paper. # These experiments have a",
"We # need to convert this to a mass flow",
"= 273.15 + 13. S = 34.5 rho = seawater.density(T,",
"for the ') print('experiments in the paper by Brandvik et",
"jet.simulate(d0, md_oil) # We compare the result to the measured",
"T = 273.15 + 13. S = 34.5 rho =",
"et al. (2013).') print('\\nComparisons are for the data reported in",
"print('\\nComparisons are for the data reported in Table 3') print('of",
"# They also used seawater (assumed salinity of 34.5 psu)",
"PureJet class in the') print('particle_size_models module of TAMOC for the",
"um\\n' % (jet.get_d50() * 1.e6)) # When dispersant is added",
"a temperature of 13 deg C T = 273.15 +",
"= particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) #",
"= np.pi * (d0 / 2.)**2 q_oil = u_oil *",
"(jet.get_d50() * 1.e6)) # When dispersant is added in sufficient",
"jet. \"\"\" # <NAME>, March 2020, Texas A&M University <<EMAIL>>.",
"may use: jet.simulate(d0, md_oil) # We compare the result to",
"of 34.5 psu) and released the # oil from a",
"md_oil) # We compare the result to the measured data",
"Brandvik et al. (2013).') print('\\nComparisons are for the data reported",
"oil, with the following reported properties rho_oil = 839.3 mu_oil",
"requires specification of all of the fluid properties of the",
"13. S = 34.5 rho = seawater.density(T, S, 101325.) P",
"paper') print('---------------------------------------------------------------') # Simulate an experiment from Brandvik et al.",
"steps involved in using the `particle_size_models.PureJet` object, which requires specification",
"np.pi * (d0 / 2.)**2 q_oil = u_oil * A_oil",
"the `particle_size_models.PureJet` object, which requires specification of all of the",
"%3.3d um\\n' % (jet.get_d50() * 1.e6)) # We can also",
"print('dispersant to oil ratio of 50 is:') print(' Measured: %3.3d",
": %3.3d um\\n' % (jet.get_d50() * 1.e6)) # We can",
"= 11.3 A_oil = np.pi * (d0 / 2.)**2 q_oil",
"= 5.e-3 sigma = 15.5e-3 # We will simulate data",
"droplet size for the no-disperant experiment is:') print(' Measured: %3.3d",
"# tension reduces and the droplet size gets smaller. At",
"in the paper by Brandvik et al. (2013).') print('\\nComparisons are",
"should # always be reported within a numpy array, which",
"=================================== Use the ``TAMOC`` `particle_size_models` module to simulate a laboratory",
"from Brandvik et al. (2013). Their data uses # Oseberg",
"101325.) P = 101325. + rho * 9.81 * 6.",
"50, sigma is: sigma = 0.05e-3 # We can run",
"median droplet size for an experiments with a') print('dispersant to",
"properties of the jet. \"\"\" # <NAME>, March 2020, Texas",
"Table 3') print('of the paper') print('---------------------------------------------------------------') # Simulate an experiment",
"sigma is: sigma = 0.05e-3 # We can run this",
"P) # With this information, we can initialize a #",
"A&M University <<EMAIL>>. from __future__ import (absolute_import, division, print_function) from",
"print('\\nThe median droplet size for the no-disperant experiment is:') print('",
"# When dispersant is added in sufficient quantities, the interfacial",
"if __name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet class",
"all of the oil properties in the # jet object",
"% 170) print(' Modeled : %3.3d um\\n' % (jet.get_d50() *",
"as follows: print('\\nThe median droplet size for an experiments with",
"= 0.05e-3 # We can run this case by updating",
"this case by updating the properties of the jet object",
"We can also plot the size distribution print('\\nThe corresponding size",
"0.0015 # They also used seawater (assumed salinity of 34.5",
"interfacial # tension reduces and the droplet size gets smaller.",
"droplet size for an experiments with a') print('dispersant to oil",
"module of TAMOC for the ') print('experiments in the paper",
"using the PureJet class in the') print('particle_size_models module of TAMOC",
"Pure Oil Jet =================================== Use the ``TAMOC`` `particle_size_models` module to",
"3 in the Brandvik et al. (2013) paper. # These",
"101325. + rho * 9.81 * 6. rho = seawater.density(T,",
"the size distribution print('\\nThe corresponding size distribution is plotted in",
"# To simulate the no-dispersant case, all of the oil",
"measured data as follows: print('\\nThe median droplet size for an",
"S = 34.5 rho = seawater.density(T, S, 101325.) P =",
"plot the size distribution print('\\nThe corresponding size distribution is plotted",
"can initialize a # `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil,",
"q_oil]) # To simulate the no-dispersant case, all of the",
"% (jet.get_d50() * 1.e6)) # We can also plot the",
"as follows: print('\\nThe median droplet size for the no-disperant experiment",
"re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type =",
"use: jet.simulate(d0, md_oil) # We compare the result to the",
"# We can run this case by updating the properties",
"1.5 mm d0 = 0.0015 # They also used seawater",
"gets smaller. At a dispersant # to oil ratio of",
"flow rate. The mass flow rate should # always be",
"fluxes for different pseudocomponents of the oil. u_oil = 11.3",
"print('\\nThe median droplet size for an experiments with a') print('dispersant",
"A_oil md_oil = np.array([rho_oil * q_oil]) # To simulate the",
"for an experiments with a') print('dispersant to oil ratio of",
"P = 101325. + rho * 9.81 * 6. rho",
"`particle_size_models.PureJet` object, which requires specification of all of the fluid",
"rho, mu, fp_type = 1) # Brandvik et al. (2013)",
"seawater.density(T, S, P) mu = seawater.mu(T, S, P) # With",
"These experiments have a nozzle diameter of 1.5 mm d0",
"Jet =================================== Use the ``TAMOC`` `particle_size_models` module to simulate a",
"15.5e-3 # We will simulate data from Table 3 in",
"Models: Pure Oil Jet =================================== Use the ``TAMOC`` `particle_size_models` module",
"We will simulate data from Table 3 in the Brandvik",
"particle_size_models import numpy as np import warnings warnings.filterwarnings(\"ignore\") if __name__",
"# re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type",
"and # re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu,",
"oil jet into water. This script demonstrates the typical steps",
"at the nozzle. We # need to convert this to",
"in the Brandvik et al. (2013) paper. # These experiments",
"simulate a laboratory scale pure oil jet into water. This",
"paper. # These experiments have a nozzle diameter of 1.5",
"a numpy array, which allows for different # mass fluxes",
"class in the') print('particle_size_models module of TAMOC for the ')",
"droplet size gets smaller. At a dispersant # to oil",
"# Simulate an experiment from Brandvik et al. (2013). Their",
"object, which requires specification of all of the fluid properties",
"m at a temperature of 13 deg C T =",
"diameter of 1.5 mm d0 = 0.0015 # They also",
"al. (2013) paper. # These experiments have a nozzle diameter",
"print('of the paper') print('---------------------------------------------------------------') # Simulate an experiment from Brandvik",
"and the droplet size gets smaller. At a dispersant #",
"reported properties rho_oil = 839.3 mu_oil = 5.e-3 sigma =",
"a') print('dispersant to oil ratio of 50 is:') print(' Measured:",
"= seawater.density(T, S, P) mu = seawater.mu(T, S, P) #",
"np.array([rho_oil * q_oil]) # To simulate the no-dispersant case, all",
"* (d0 / 2.)**2 q_oil = u_oil * A_oil md_oil",
"%3.3d um\\n' % (jet.get_d50() * 1.e6)) # When dispersant is",
"reported in Table 3') print('of the paper') print('---------------------------------------------------------------') # Simulate",
"al. (2013). Their data uses # Oseberg oil, with the",
"et al. (2013) paper. # These experiments have a nozzle",
"a dispersant # to oil ratio of 50, sigma is:",
"experiment is:') print(' Measured: %3.3d um' % 237) print(' Modeled",
"Oseberg oil, with the following reported properties rho_oil = 839.3",
"273.15 + 13. S = 34.5 rho = seawater.density(T, S,",
"quantities, the interfacial # tension reduces and the droplet size",
"of the fluid properties of the jet. \"\"\" # <NAME>,",
"for different # mass fluxes for different pseudocomponents of the",
"using the `particle_size_models.PureJet` object, which requires specification of all of",
"# We compare the result to the measured data as",
"exit velocity at the nozzle. We # need to convert",
"a laboratory scale pure oil jet into water. This script",
"* 1.e6)) # We can also plot the size distribution",
"'__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet class in the') print('particle_size_models",
"Modeled : %3.3d um\\n' % (jet.get_d50() * 1.e6)) # When",
"mu = seawater.mu(T, S, P) # With this information, we",
"of the oil properties in the # jet object are",
"data as follows: print('\\nThe median droplet size for the no-disperant",
"* 1.e6)) # When dispersant is added in sufficient quantities,",
"result to the measured data as follows: print('\\nThe median droplet",
"import numpy as np import warnings warnings.filterwarnings(\"ignore\") if __name__ ==",
"can run this case by updating the properties of the",
"# mass fluxes for different pseudocomponents of the oil. u_oil",
"to simulate a laboratory scale pure oil jet into water.",
"Their data uses # Oseberg oil, with the following reported",
"Modeled : %3.3d um\\n' % (jet.get_d50() * 1.e6)) # We",
"run this case by updating the properties of the jet",
"object are currently correct. Hence, we may use: jet.simulate(d0, md_oil)",
"division, print_function) from tamoc import seawater, particle_size_models import numpy as",
"will simulate data from Table 3 in the Brandvik et",
"convert this to a mass flow rate. The mass flow",
"simulate the no-dispersant case, all of the oil properties in",
"case, all of the oil properties in the # jet",
"<reponame>ChrisBarker-NOAA/tamoc \"\"\" Particle Size Models: Pure Oil Jet =================================== Use",
"al. (2013) report the exit velocity at the nozzle. We",
"%3.3d um' % 170) print(' Modeled : %3.3d um\\n' %",
"seawater.density(T, S, 101325.) P = 101325. + rho * 9.81",
"%3.3d um' % 237) print(' Modeled : %3.3d um\\n' %",
"print(' Modeled : %3.3d um\\n' % (jet.get_d50() * 1.e6)) #",
"170) print(' Modeled : %3.3d um\\n' % (jet.get_d50() * 1.e6))",
"size for the no-disperant experiment is:') print(' Measured: %3.3d um'",
"S, P) mu = seawater.mu(T, S, P) # With this",
"# jet object are currently correct. Hence, we may use:",
"the exit velocity at the nozzle. We # need to",
"(2013). Their data uses # Oseberg oil, with the following",
"this information, we can initialize a # `particle_size_models.PureJet` object jet",
"of 13 deg C T = 273.15 + 13. S",
"temperature of 13 deg C T = 273.15 + 13.",
"= 1) jet.simulate(d0, md_oil) # We compare the result to",
"# These experiments have a nozzle diameter of 1.5 mm",
"* 9.81 * 6. rho = seawater.density(T, S, P) mu",
"u_oil = 11.3 A_oil = np.pi * (d0 / 2.)**2",
"the oil. u_oil = 11.3 A_oil = np.pi * (d0",
"tension reduces and the droplet size gets smaller. At a",
"+ 13. S = 34.5 rho = seawater.density(T, S, 101325.)",
"rho_oil = 839.3 mu_oil = 5.e-3 sigma = 15.5e-3 #",
"in Table 3') print('of the paper') print('---------------------------------------------------------------') # Simulate an",
"# always be reported within a numpy array, which allows",
"A_oil = np.pi * (d0 / 2.)**2 q_oil = u_oil",
"To simulate the no-dispersant case, all of the oil properties",
"we can initialize a # `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil,",
"ratio of 50, sigma is: sigma = 0.05e-3 # We",
"of about 6 m at a temperature of 13 deg",
"Oil Jet =================================== Use the ``TAMOC`` `particle_size_models` module to simulate",
"of the jet. \"\"\" # <NAME>, March 2020, Texas A&M",
"the following reported properties rho_oil = 839.3 mu_oil = 5.e-3",
"the result to the measured data as follows: print('\\nThe median",
"(d0 / 2.)**2 q_oil = u_oil * A_oil md_oil =",
"1.e6)) # We can also plot the size distribution print('\\nThe",
"oil properties in the # jet object are currently correct.",
"of TAMOC for the ') print('experiments in the paper by",
"um' % 237) print(' Modeled : %3.3d um\\n' % (jet.get_d50()",
"(2013) report the exit velocity at the nozzle. We #",
"need to convert this to a mass flow rate. The",
"size for an experiments with a') print('dispersant to oil ratio",
"dispersant is added in sufficient quantities, the interfacial # tension",
"for the data reported in Table 3') print('of the paper')",
"the paper by Brandvik et al. (2013).') print('\\nComparisons are for",
"print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet class in the') print('particle_size_models module",
"np import warnings warnings.filterwarnings(\"ignore\") if __name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration",
"the no-disperant experiment is:') print(' Measured: %3.3d um' % 237)",
"Measured: %3.3d um' % 170) print(' Modeled : %3.3d um\\n'",
"salinity of 34.5 psu) and released the # oil from",
"used seawater (assumed salinity of 34.5 psu) and released the",
"a # `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho,",
"and released the # oil from a depth of about",
"with a') print('dispersant to oil ratio of 50 is:') print('",
"data as follows: print('\\nThe median droplet size for an experiments",
"depth of about 6 m at a temperature of 13",
"a depth of about 6 m at a temperature of",
"9.81 * 6. rho = seawater.density(T, S, P) mu =",
"the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1)",
"the paper') print('---------------------------------------------------------------') # Simulate an experiment from Brandvik et",
"jet object and # re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma,",
"reported within a numpy array, which allows for different #",
"= np.array([rho_oil * q_oil]) # To simulate the no-dispersant case,",
"the measured data as follows: print('\\nThe median droplet size for",
"et al. (2013) report the exit velocity at the nozzle.",
"to oil ratio of 50 is:') print(' Measured: %3.3d um'",
"the oil properties in the # jet object are currently",
"simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) jet.simulate(d0,",
"no-dispersant case, all of the oil properties in the #",
"') print('experiments in the paper by Brandvik et al. (2013).')",
"flow rate should # always be reported within a numpy",
"currently correct. Hence, we may use: jet.simulate(d0, md_oil) # We",
"simulate data from Table 3 in the Brandvik et al.",
"is:') print(' Measured: %3.3d um' % 170) print(' Modeled :",
"sigma = 0.05e-3 # We can run this case by",
"= 1) # Brandvik et al. (2013) report the exit",
"the data reported in Table 3') print('of the paper') print('---------------------------------------------------------------')",
"% (jet.get_d50() * 1.e6)) # When dispersant is added in",
"# Oseberg oil, with the following reported properties rho_oil =",
"correct. Hence, we may use: jet.simulate(d0, md_oil) # We compare",
"laboratory scale pure oil jet into water. This script demonstrates",
"also used seawater (assumed salinity of 34.5 psu) and released",
"Measured: %3.3d um' % 237) print(' Modeled : %3.3d um\\n'",
"# With this information, we can initialize a # `particle_size_models.PureJet`",
"information, we can initialize a # `particle_size_models.PureJet` object jet =",
"within a numpy array, which allows for different # mass",
"follows: print('\\nThe median droplet size for the no-disperant experiment is:')",
"Simulate an experiment from Brandvik et al. (2013). Their data",
"* A_oil md_oil = np.array([rho_oil * q_oil]) # To simulate",
"md_oil = np.array([rho_oil * q_oil]) # To simulate the no-dispersant",
"= 0.0015 # They also used seawater (assumed salinity of",
"of the oil. u_oil = 11.3 A_oil = np.pi *",
"5.e-3 sigma = 15.5e-3 # We will simulate data from",
"fluid properties of the jet. \"\"\" # <NAME>, March 2020,",
"to a mass flow rate. The mass flow rate should",
"% 237) print(' Modeled : %3.3d um\\n' % (jet.get_d50() *",
"50 is:') print(' Measured: %3.3d um' % 170) print(' Modeled",
"# Brandvik et al. (2013) report the exit velocity at",
"numpy as np import warnings warnings.filterwarnings(\"ignore\") if __name__ == '__main__':",
"\"\"\" # <NAME>, March 2020, Texas A&M University <<EMAIL>>. from",
"fp_type = 1) # Brandvik et al. (2013) report the",
"When dispersant is added in sufficient quantities, the interfacial #",
"script demonstrates the typical steps involved in using the `particle_size_models.PureJet`",
"* q_oil]) # To simulate the no-dispersant case, all of",
"with the following reported properties rho_oil = 839.3 mu_oil =",
"= 839.3 mu_oil = 5.e-3 sigma = 15.5e-3 # We",
"# `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu,",
"from tamoc import seawater, particle_size_models import numpy as np import",
"__name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet class in",
"# need to convert this to a mass flow rate.",
"properties in the # jet object are currently correct. Hence,",
"released the # oil from a depth of about 6",
"experiment from Brandvik et al. (2013). Their data uses #",
"= 15.5e-3 # We will simulate data from Table 3",
"(2013).') print('\\nComparisons are for the data reported in Table 3')",
"case by updating the properties of the jet object and",
"rate should # always be reported within a numpy array,",
"also plot the size distribution print('\\nThe corresponding size distribution is",
"2020, Texas A&M University <<EMAIL>>. from __future__ import (absolute_import, division,",
"this to a mass flow rate. The mass flow rate",
"# We will simulate data from Table 3 in the",
"experiments with a') print('dispersant to oil ratio of 50 is:')",
"of 50 is:') print(' Measured: %3.3d um' % 170) print('",
"# <NAME>, March 2020, Texas A&M University <<EMAIL>>. from __future__",
"= 34.5 rho = seawater.density(T, S, 101325.) P = 101325.",
"different # mass fluxes for different pseudocomponents of the oil.",
"be reported within a numpy array, which allows for different",
"are currently correct. Hence, we may use: jet.simulate(d0, md_oil) #",
"``TAMOC`` `particle_size_models` module to simulate a laboratory scale pure oil",
"seawater, particle_size_models import numpy as np import warnings warnings.filterwarnings(\"ignore\") if",
"by updating the properties of the jet object and #",
"print('experiments in the paper by Brandvik et al. (2013).') print('\\nComparisons",
"in the # jet object are currently correct. Hence, we",
"compare the result to the measured data as follows: print('\\nThe",
"/ 2.)**2 q_oil = u_oil * A_oil md_oil = np.array([rho_oil",
"(jet.get_d50() * 1.e6)) # We can also plot the size",
"always be reported within a numpy array, which allows for",
"is: sigma = 0.05e-3 # We can run this case",
"sigma = 15.5e-3 # We will simulate data from Table",
"all of the fluid properties of the jet. \"\"\" #",
"updating the properties of the jet object and # re-running",
"q_oil = u_oil * A_oil md_oil = np.array([rho_oil * q_oil])",
"mm d0 = 0.0015 # They also used seawater (assumed",
"13 deg C T = 273.15 + 13. S =",
"oil from a depth of about 6 m at a",
"1) # Brandvik et al. (2013) report the exit velocity",
"Hence, we may use: jet.simulate(d0, md_oil) # We compare the",
"the typical steps involved in using the `particle_size_models.PureJet` object, which",
"d0 = 0.0015 # They also used seawater (assumed salinity",
"6. rho = seawater.density(T, S, P) mu = seawater.mu(T, S,",
"the no-dispersant case, all of the oil properties in the",
"demonstrates the typical steps involved in using the `particle_size_models.PureJet` object,",
"the droplet size gets smaller. At a dispersant # to",
"to oil ratio of 50, sigma is: sigma = 0.05e-3",
"specification of all of the fluid properties of the jet.",
"Table 3 in the Brandvik et al. (2013) paper. #",
"print('---------------------------------------------------------------') # Simulate an experiment from Brandvik et al. (2013).",
"With this information, we can initialize a # `particle_size_models.PureJet` object",
"sigma, rho, mu, fp_type = 1) jet.simulate(d0, md_oil) # We",
"an experiments with a') print('dispersant to oil ratio of 50",
"rho = seawater.density(T, S, 101325.) P = 101325. + rho",
"size distribution print('\\nThe corresponding size distribution is plotted in Figure",
"sigma, rho, mu, fp_type = 1) # Brandvik et al.",
"<<EMAIL>>. from __future__ import (absolute_import, division, print_function) from tamoc import",
"3') print('of the paper') print('---------------------------------------------------------------') # Simulate an experiment from",
"which allows for different # mass fluxes for different pseudocomponents",
"properties of the jet object and # re-running the simualtion",
"the # oil from a depth of about 6 m",
"# to oil ratio of 50, sigma is: sigma =",
"the ``TAMOC`` `particle_size_models` module to simulate a laboratory scale pure",
"are for the data reported in Table 3') print('of the",
"particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) # Brandvik",
"237) print(' Modeled : %3.3d um\\n' % (jet.get_d50() * 1.e6))",
"al. (2013).') print('\\nComparisons are for the data reported in Table",
"can also plot the size distribution print('\\nThe corresponding size distribution",
"is added in sufficient quantities, the interfacial # tension reduces",
"Brandvik et al. (2013) report the exit velocity at the",
"array, which allows for different # mass fluxes for different",
"oil ratio of 50, sigma is: sigma = 0.05e-3 #",
"scale pure oil jet into water. This script demonstrates the",
"ratio of 50 is:') print(' Measured: %3.3d um' % 170)",
"= seawater.mu(T, S, P) # With this information, we can",
"by Brandvik et al. (2013).') print('\\nComparisons are for the data",
"corresponding size distribution is plotted in Figure 1') jet.get_distributions(15) jet.plot_psd(1)",
"the jet object and # re-running the simualtion jet.update_properties(rho_oil, mu_oil,",
"warnings warnings.filterwarnings(\"ignore\") if __name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the",
"the ') print('experiments in the paper by Brandvik et al.",
"we may use: jet.simulate(d0, md_oil) # We compare the result",
"34.5 psu) and released the # oil from a depth",
"rho = seawater.density(T, S, P) mu = seawater.mu(T, S, P)",
"a mass flow rate. The mass flow rate should #",
"print(' Measured: %3.3d um' % 237) print(' Modeled : %3.3d",
"We can run this case by updating the properties of",
"et al. (2013). Their data uses # Oseberg oil, with",
"# oil from a depth of about 6 m at",
"print_function) from tamoc import seawater, particle_size_models import numpy as np",
"<NAME>, March 2020, Texas A&M University <<EMAIL>>. from __future__ import",
"uses # Oseberg oil, with the following reported properties rho_oil",
"mass flow rate should # always be reported within a",
"rho * 9.81 * 6. rho = seawater.density(T, S, P)",
"mu_oil, sigma, rho, mu, fp_type = 1) # Brandvik et",
"Particle Size Models: Pure Oil Jet =================================== Use the ``TAMOC``",
"print('particle_size_models module of TAMOC for the ') print('experiments in the",
"report the exit velocity at the nozzle. We # need",
"data reported in Table 3') print('of the paper') print('---------------------------------------------------------------') #",
"mu_oil = 5.e-3 sigma = 15.5e-3 # We will simulate",
"data from Table 3 in the Brandvik et al. (2013)",
"(absolute_import, division, print_function) from tamoc import seawater, particle_size_models import numpy",
"object and # re-running the simualtion jet.update_properties(rho_oil, mu_oil, sigma, rho,",
"the PureJet class in the') print('particle_size_models module of TAMOC for",
"import warnings warnings.filterwarnings(\"ignore\") if __name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using",
"print('\\nThe corresponding size distribution is plotted in Figure 1') jet.get_distributions(15)",
"oil ratio of 50 is:') print(' Measured: %3.3d um' %",
"for the no-disperant experiment is:') print(' Measured: %3.3d um' %",
"P) mu = seawater.mu(T, S, P) # With this information,",
"in the') print('particle_size_models module of TAMOC for the ') print('experiments",
"the # jet object are currently correct. Hence, we may",
"as np import warnings warnings.filterwarnings(\"ignore\") if __name__ == '__main__': print('\\n---------------------------------------------------------------')",
"Brandvik et al. (2013). Their data uses # Oseberg oil,",
"(2013) paper. # These experiments have a nozzle diameter of",
"object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type =",
"have a nozzle diameter of 1.5 mm d0 = 0.0015",
"nozzle diameter of 1.5 mm d0 = 0.0015 # They",
"initialize a # `particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma,",
"into water. This script demonstrates the typical steps involved in",
"== '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet class in the')",
"mu_oil, sigma, rho, mu, fp_type = 1) jet.simulate(d0, md_oil) #",
"the Brandvik et al. (2013) paper. # These experiments have",
"the fluid properties of the jet. \"\"\" # <NAME>, March",
"11.3 A_oil = np.pi * (d0 / 2.)**2 q_oil =",
"of the jet object and # re-running the simualtion jet.update_properties(rho_oil,",
"sufficient quantities, the interfacial # tension reduces and the droplet",
"1.e6)) # When dispersant is added in sufficient quantities, the",
"measured data as follows: print('\\nThe median droplet size for the",
"from __future__ import (absolute_import, division, print_function) from tamoc import seawater,",
"um' % 170) print(' Modeled : %3.3d um\\n' % (jet.get_d50()",
"At a dispersant # to oil ratio of 50, sigma",
"`particle_size_models.PureJet` object jet = particle_size_models.PureJet(rho_oil, mu_oil, sigma, rho, mu, fp_type",
"um\\n' % (jet.get_d50() * 1.e6)) # We can also plot",
"involved in using the `particle_size_models.PureJet` object, which requires specification of",
"1) jet.simulate(d0, md_oil) # We compare the result to the",
"(assumed salinity of 34.5 psu) and released the # oil",
": %3.3d um\\n' % (jet.get_d50() * 1.e6)) # When dispersant",
"to convert this to a mass flow rate. The mass",
"the jet. \"\"\" # <NAME>, March 2020, Texas A&M University",
"smaller. At a dispersant # to oil ratio of 50,",
"typical steps involved in using the `particle_size_models.PureJet` object, which requires",
"at a temperature of 13 deg C T = 273.15",
"an experiment from Brandvik et al. (2013). Their data uses",
"reduces and the droplet size gets smaller. At a dispersant",
"= seawater.density(T, S, 101325.) P = 101325. + rho *",
"numpy array, which allows for different # mass fluxes for",
"is:') print(' Measured: %3.3d um' % 237) print(' Modeled :",
"pure oil jet into water. This script demonstrates the typical",
"of 1.5 mm d0 = 0.0015 # They also used",
"+ rho * 9.81 * 6. rho = seawater.density(T, S,",
"= u_oil * A_oil md_oil = np.array([rho_oil * q_oil]) #",
"the interfacial # tension reduces and the droplet size gets",
"u_oil * A_oil md_oil = np.array([rho_oil * q_oil]) # To",
"rho, mu, fp_type = 1) jet.simulate(d0, md_oil) # We compare",
"Size Models: Pure Oil Jet =================================== Use the ``TAMOC`` `particle_size_models`",
"in sufficient quantities, the interfacial # tension reduces and the",
"print(' Measured: %3.3d um' % 170) print(' Modeled : %3.3d",
"of all of the fluid properties of the jet. \"\"\"",
"paper by Brandvik et al. (2013).') print('\\nComparisons are for the",
"seawater.mu(T, S, P) # With this information, we can initialize",
"which requires specification of all of the fluid properties of",
"allows for different # mass fluxes for different pseudocomponents of",
"This script demonstrates the typical steps involved in using the",
"deg C T = 273.15 + 13. S = 34.5",
"distribution print('\\nThe corresponding size distribution is plotted in Figure 1')",
"mass fluxes for different pseudocomponents of the oil. u_oil =",
"water. This script demonstrates the typical steps involved in using",
"\"\"\" Particle Size Models: Pure Oil Jet =================================== Use the",
"* 6. rho = seawater.density(T, S, P) mu = seawater.mu(T,",
"in using the `particle_size_models.PureJet` object, which requires specification of all",
"import (absolute_import, division, print_function) from tamoc import seawater, particle_size_models import",
"the nozzle. We # need to convert this to a",
"following reported properties rho_oil = 839.3 mu_oil = 5.e-3 sigma",
"jet.update_properties(rho_oil, mu_oil, sigma, rho, mu, fp_type = 1) jet.simulate(d0, md_oil)",
"0.05e-3 # We can run this case by updating the",
"6 m at a temperature of 13 deg C T",
"for different pseudocomponents of the oil. u_oil = 11.3 A_oil",
"the') print('particle_size_models module of TAMOC for the ') print('experiments in",
"S, P) # With this information, we can initialize a",
"from a depth of about 6 m at a temperature",
"follows: print('\\nThe median droplet size for an experiments with a')",
"from Table 3 in the Brandvik et al. (2013) paper.",
"jet into water. This script demonstrates the typical steps involved",
"pseudocomponents of the oil. u_oil = 11.3 A_oil = np.pi",
"`particle_size_models` module to simulate a laboratory scale pure oil jet",
"March 2020, Texas A&M University <<EMAIL>>. from __future__ import (absolute_import,",
"warnings.filterwarnings(\"ignore\") if __name__ == '__main__': print('\\n---------------------------------------------------------------') print('Demonstration using the PureJet"
] |
[
"needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def stop(): n = hub.findActor(name)",
"import tron.Misc from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import",
"cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds = ('ping', 'status',",
"debug=1) nub = SocketActorNub( poller, cfg['host'], cfg['port'], name=name, encoder=e, decoder=d,",
"poller, cfg['host'], cfg['port'], name=name, encoder=e, decoder=d, grabCID=True, # the actor",
"'hal' def start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds",
"generates a line we can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir,",
"import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import",
"'version') safeCmdsList = ['ping', 'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d",
"from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder",
"= ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub =",
"name), debug=3) hub.addActor(nub) def stop(): n = hub.findActor(name) if n:",
"useCID=False, debug=1) nub = SocketActorNub( poller, cfg['host'], cfg['port'], name=name, encoder=e,",
"import os.path import tron.Misc from tron import g, hub from",
"from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name =",
"safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True,",
"def start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds =",
"tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub",
"SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal' def start(poller):",
"tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal'",
"cfg['host'], cfg['port'], name=name, encoder=e, decoder=d, grabCID=True, # the actor spontaneously",
"tron.Misc from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder",
"cfg['port'], name=name, encoder=e, decoder=d, grabCID=True, # the actor spontaneously generates",
"encoder=e, decoder=d, grabCID=True, # the actor spontaneously generates a line",
"logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def stop(): n = hub.findActor(name) if",
"import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal' def",
"SocketActorNub( poller, cfg['host'], cfg['port'], name=name, encoder=e, decoder=d, grabCID=True, # the",
"= r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False,",
"ASCIIReplyDecoder name = 'hal' def start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors',",
"ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name",
"actor spontaneously generates a line we can eat. initCmds=initCmds, safeCmds=safeCmds,",
"grabCID=True, # the actor spontaneously generates a line we can",
"= SocketActorNub( poller, cfg['host'], cfg['port'], name=name, encoder=e, decoder=d, grabCID=True, #",
"name=name, encoder=e, decoder=d, grabCID=True, # the actor spontaneously generates a",
"e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub = SocketActorNub( poller, cfg['host'],",
"= ['ping', 'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True,",
"= 'hal' def start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop()",
"hub.addActor(nub) def stop(): n = hub.findActor(name) if n: hub.dropActor(n) del",
"can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def",
"r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1)",
"we can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub)",
"tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import",
"spontaneously generates a line we can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True,",
"start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds = ('ping',",
"'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1) e =",
"stop() initCmds = ('ping', 'status', 'version') safeCmdsList = ['ping', 'version',",
"nub = SocketActorNub( poller, cfg['host'], cfg['port'], name=name, encoder=e, decoder=d, grabCID=True,",
"safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def stop(): n =",
"debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub = SocketActorNub( poller,",
"'actors', doFlush=True)[name] stop() initCmds = ('ping', 'status', 'version') safeCmdsList =",
"= ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub = SocketActorNub( poller, cfg['host'], cfg['port'],",
"# the actor spontaneously generates a line we can eat.",
"a line we can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name),",
"from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal' def start(poller): cfg",
"('ping', 'status', 'version') safeCmdsList = ['ping', 'version', 'status'] safeCmds =",
"eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def stop():",
"g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub",
"tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder name = 'hal' def start(poller): cfg =",
"hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from",
"ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub = SocketActorNub(",
"'status', 'version') safeCmdsList = ['ping', 'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList))",
"from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder import ASCIICmdEncoder from",
"= ('ping', 'status', 'version') safeCmdsList = ['ping', 'version', 'status'] safeCmds",
"line we can eat. initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3)",
"os.path import tron.Misc from tron import g, hub from tron.Hub.Command.Encoders.ASCIICmdEncoder",
"initCmds = ('ping', 'status', 'version') safeCmdsList = ['ping', 'version', 'status']",
"debug=3) hub.addActor(nub) def stop(): n = hub.findActor(name) if n: hub.dropActor(n)",
"initCmds=initCmds, safeCmds=safeCmds, needsAuth=True, logDir=os.path.join(g.logDir, name), debug=3) hub.addActor(nub) def stop(): n",
"name = 'hal' def start(poller): cfg = tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name]",
"the actor spontaneously generates a line we can eat. initCmds=initCmds,",
"= tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds = ('ping', 'status', 'version')",
"tron.Misc.cfg.get(g.location, 'actors', doFlush=True)[name] stop() initCmds = ('ping', 'status', 'version') safeCmdsList",
"decoder=d, grabCID=True, # the actor spontaneously generates a line we",
"import ASCIIReplyDecoder name = 'hal' def start(poller): cfg = tron.Misc.cfg.get(g.location,",
"'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1) e",
"def stop(): n = hub.findActor(name) if n: hub.dropActor(n) del n",
"import ASCIICmdEncoder from tron.Hub.Nub.SocketActorNub import SocketActorNub from tron.Hub.Reply.Decoders.ASCIIReplyDecoder import ASCIIReplyDecoder",
"ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub = SocketActorNub( poller, cfg['host'], cfg['port'], name=name,",
"safeCmdsList = ['ping', 'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d =",
"d = ASCIIReplyDecoder(cidFirst=True, debug=1) e = ASCIICmdEncoder(sendCommander=True, useCID=False, debug=1) nub",
"['ping', 'version', 'status'] safeCmds = r'^\\s*({0})\\s*$'.format('|'.join(safeCmdsList)) d = ASCIIReplyDecoder(cidFirst=True, debug=1)",
"doFlush=True)[name] stop() initCmds = ('ping', 'status', 'version') safeCmdsList = ['ping',"
] |
[
"dataclass, field from decimal import Decimal from typing import Optional",
"eff_date: Optional[XmlDate] = field( default=None, metadata={ \"name\": \"effDate\", \"type\": \"Attribute\",",
"default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", \"required\": True, } )",
"import Decimal from typing import Optional from xsdata.models.datatype import XmlDate",
"\"Element\", \"namespace\": \"\", } ) comment: Optional[str] = field( default=None,",
"<reponame>gramm/xsdata from dataclasses import dataclass, field from decimal import Decimal",
"number: Optional[int] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\",",
"field( default=None, metadata={ \"type\": \"Attribute\", } ) eff_date: Optional[XmlDate] =",
"Optional from xsdata.models.datatype import XmlDate @dataclass class SizeType: value: Optional[int]",
"dataclasses import dataclass, field from decimal import Decimal from typing",
"\"\", } ) name: Optional[str] = field( default=None, metadata={ \"type\":",
"default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) number: Optional[int]",
"id: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", \"required\": True,",
"\"Attribute\", \"required\": True, } ) version: Optional[Decimal] = field( default=None,",
"metadata={ \"type\": \"Attribute\", } ) eff_date: Optional[XmlDate] = field( default=None,",
"\"type\": \"Element\", \"namespace\": \"\", } ) comment: Optional[str] = field(",
"metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) name: Optional[str] =",
"field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) size:",
"field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) number:",
"\"type\": \"Element\", \"namespace\": \"\", } ) name: Optional[str] = field(",
"\"type\": \"Element\", \"namespace\": \"\", } ) number: Optional[int] = field(",
"import dataclass, field from decimal import Decimal from typing import",
"field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) name:",
"class ShirtType: description: Optional[str] = field( default=None, metadata={ \"type\": \"Element\",",
"field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) comment:",
"True, } ) system: Optional[str] = field( default=None, metadata={ \"type\":",
"default=None, metadata={ \"type\": \"Attribute\", } ) @dataclass class ShirtType: description:",
"\"\", } ) comment: Optional[str] = field( default=None, metadata={ \"type\":",
"field( default=None, metadata={ \"type\": \"Attribute\", } ) @dataclass class ShirtType:",
"= field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", \"required\": True,",
"ShirtType: description: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\":",
"metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) comment: Optional[str] =",
") size: Optional[SizeType] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\":",
"Optional[XmlDate] = field( default=None, metadata={ \"name\": \"effDate\", \"type\": \"Attribute\", }",
"default=None, metadata={ \"name\": \"effDate\", \"type\": \"Attribute\", } ) @dataclass class",
"metadata={ \"required\": True, } ) system: Optional[str] = field( default=None,",
"@dataclass class SizeType: value: Optional[int] = field( default=None, metadata={ \"required\":",
"\"namespace\": \"\", } ) comment: Optional[str] = field( default=None, metadata={",
"SizeType: value: Optional[int] = field( default=None, metadata={ \"required\": True, }",
"\"type\": \"Attribute\", \"required\": True, } ) version: Optional[Decimal] = field(",
"from xsdata.models.datatype import XmlDate @dataclass class SizeType: value: Optional[int] =",
"class SizeType: value: Optional[int] = field( default=None, metadata={ \"required\": True,",
"True, } ) version: Optional[Decimal] = field( default=None, metadata={ \"type\":",
"XmlDate @dataclass class SizeType: value: Optional[int] = field( default=None, metadata={",
"\"namespace\": \"\", } ) name: Optional[str] = field( default=None, metadata={",
"default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) name: Optional[str]",
"field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", \"required\": True, }",
"\"Attribute\", } ) @dataclass class ShirtType: description: Optional[str] = field(",
"} ) number: Optional[int] = field( default=None, metadata={ \"type\": \"Element\",",
") comment: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\":",
"} ) system: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\",",
"} ) name: Optional[str] = field( default=None, metadata={ \"type\": \"Element\",",
"from typing import Optional from xsdata.models.datatype import XmlDate @dataclass class",
"default=None, metadata={ \"type\": \"Attribute\", } ) eff_date: Optional[XmlDate] = field(",
"} ) size: Optional[SizeType] = field( default=None, metadata={ \"type\": \"Element\",",
"\"type\": \"Attribute\", } ) @dataclass class ShirtType: description: Optional[str] =",
"metadata={ \"type\": \"Attribute\", \"required\": True, } ) version: Optional[Decimal] =",
"comment: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\",",
"from decimal import Decimal from typing import Optional from xsdata.models.datatype",
"\"namespace\": \"\", } ) size: Optional[SizeType] = field( default=None, metadata={",
"\"Element\", \"namespace\": \"\", \"required\": True, } ) id: Optional[str] =",
"Optional[int] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", }",
"} ) version: Optional[Decimal] = field( default=None, metadata={ \"type\": \"Attribute\",",
"} ) @dataclass class ShirtType: description: Optional[str] = field( default=None,",
"default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) comment: Optional[str]",
"\"name\": \"effDate\", \"type\": \"Attribute\", } ) @dataclass class Shirt(ShirtType): class",
"\"required\": True, } ) system: Optional[str] = field( default=None, metadata={",
"\"Attribute\", } ) eff_date: Optional[XmlDate] = field( default=None, metadata={ \"name\":",
"\"\", \"required\": True, } ) id: Optional[str] = field( default=None,",
"metadata={ \"name\": \"effDate\", \"type\": \"Attribute\", } ) @dataclass class Shirt(ShirtType):",
"version: Optional[Decimal] = field( default=None, metadata={ \"type\": \"Attribute\", } )",
"\"effDate\", \"type\": \"Attribute\", } ) @dataclass class Shirt(ShirtType): class Meta:",
"value: Optional[int] = field( default=None, metadata={ \"required\": True, } )",
"description: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\",",
"Optional[Decimal] = field( default=None, metadata={ \"type\": \"Attribute\", } ) eff_date:",
"\"Element\", \"namespace\": \"\", } ) size: Optional[SizeType] = field( default=None,",
"field from decimal import Decimal from typing import Optional from",
"\"\", } ) number: Optional[int] = field( default=None, metadata={ \"type\":",
") id: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", \"required\":",
"\"type\": \"Attribute\", } ) @dataclass class Shirt(ShirtType): class Meta: name",
"decimal import Decimal from typing import Optional from xsdata.models.datatype import",
"default=None, metadata={ \"type\": \"Attribute\", \"required\": True, } ) version: Optional[Decimal]",
"\"\", } ) size: Optional[SizeType] = field( default=None, metadata={ \"type\":",
"Decimal from typing import Optional from xsdata.models.datatype import XmlDate @dataclass",
"Optional[SizeType] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", \"required\":",
") name: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\":",
"= field( default=None, metadata={ \"type\": \"Attribute\", \"required\": True, } )",
"import XmlDate @dataclass class SizeType: value: Optional[int] = field( default=None,",
"metadata={ \"type\": \"Element\", \"namespace\": \"\", \"required\": True, } ) id:",
"default=None, metadata={ \"required\": True, } ) system: Optional[str] = field(",
"\"required\": True, } ) id: Optional[str] = field( default=None, metadata={",
"\"Attribute\", } ) @dataclass class Shirt(ShirtType): class Meta: name =",
"from dataclasses import dataclass, field from decimal import Decimal from",
"} ) @dataclass class Shirt(ShirtType): class Meta: name = \"shirt\"",
"default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) size: Optional[SizeType]",
"metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) size: Optional[SizeType] =",
"} ) comment: Optional[str] = field( default=None, metadata={ \"type\": \"Element\",",
"metadata={ \"type\": \"Element\", \"namespace\": \"\", } ) number: Optional[int] =",
"} ) eff_date: Optional[XmlDate] = field( default=None, metadata={ \"name\": \"effDate\",",
"= field( default=None, metadata={ \"type\": \"Attribute\", } ) eff_date: Optional[XmlDate]",
"field( default=None, metadata={ \"name\": \"effDate\", \"type\": \"Attribute\", } ) @dataclass",
"xsdata.models.datatype import XmlDate @dataclass class SizeType: value: Optional[int] = field(",
") system: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", }",
") version: Optional[Decimal] = field( default=None, metadata={ \"type\": \"Attribute\", }",
"Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", \"required\": True, }",
"= field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", } )",
"} ) id: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\",",
"size: Optional[SizeType] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\",",
"typing import Optional from xsdata.models.datatype import XmlDate @dataclass class SizeType:",
") number: Optional[int] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\":",
"= field( default=None, metadata={ \"name\": \"effDate\", \"type\": \"Attribute\", } )",
"Optional[int] = field( default=None, metadata={ \"required\": True, } ) system:",
"\"Element\", \"namespace\": \"\", } ) number: Optional[int] = field( default=None,",
"Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\", }",
"import Optional from xsdata.models.datatype import XmlDate @dataclass class SizeType: value:",
"name: Optional[str] = field( default=None, metadata={ \"type\": \"Element\", \"namespace\": \"\",",
"\"type\": \"Attribute\", } ) eff_date: Optional[XmlDate] = field( default=None, metadata={",
"True, } ) id: Optional[str] = field( default=None, metadata={ \"type\":",
"= field( default=None, metadata={ \"required\": True, } ) system: Optional[str]",
"field( default=None, metadata={ \"required\": True, } ) system: Optional[str] =",
"\"type\": \"Element\", \"namespace\": \"\", } ) size: Optional[SizeType] = field(",
"\"required\": True, } ) version: Optional[Decimal] = field( default=None, metadata={",
"\"Element\", \"namespace\": \"\", } ) name: Optional[str] = field( default=None,",
") @dataclass class ShirtType: description: Optional[str] = field( default=None, metadata={",
"\"namespace\": \"\", } ) number: Optional[int] = field( default=None, metadata={",
"\"namespace\": \"\", \"required\": True, } ) id: Optional[str] = field(",
"metadata={ \"type\": \"Attribute\", } ) @dataclass class ShirtType: description: Optional[str]",
") eff_date: Optional[XmlDate] = field( default=None, metadata={ \"name\": \"effDate\", \"type\":",
"@dataclass class ShirtType: description: Optional[str] = field( default=None, metadata={ \"type\":",
"system: Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", } )",
"field( default=None, metadata={ \"type\": \"Attribute\", \"required\": True, } ) version:",
"= field( default=None, metadata={ \"type\": \"Attribute\", } ) @dataclass class",
"\"type\": \"Element\", \"namespace\": \"\", \"required\": True, } ) id: Optional[str]",
"Optional[str] = field( default=None, metadata={ \"type\": \"Attribute\", } ) @dataclass"
] |
[
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"# coding: utf-8 # # Copyright 2014 The Oppia Authors.",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"All Rights Reserved. # # Licensed under the Apache License,",
"2.0 (the \"License\"); # you may not use this file",
"file except in compliance with the License. # You may",
"agreed to in writing, software # distributed under the License",
"Unless required by applicable law or agreed to in writing,",
"the License is distributed on an \"AS-IS\" BASIS, # WITHOUT",
"<gh_stars>1-10 # coding: utf-8 # # Copyright 2014 The Oppia",
"\"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"The Oppia Authors. All Rights Reserved. # # Licensed under",
"def __init__(self, name, description, schema, default_value): self.name = name self.description",
"the specific language governing permissions and # limitations under the",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"import absolute_import # pylint: disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value",
"# Copyright 2014 The Oppia Authors. All Rights Reserved. #",
"except in compliance with the License. # You may obtain",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a customization arg specification.\"\"\" def",
"# limitations under the License. \"\"\"Domain objects used within multiple",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"not use this file except in compliance with the License.",
"Copyright 2014 The Oppia Authors. All Rights Reserved. # #",
"under the License. \"\"\"Domain objects used within multiple extensions.\"\"\" from",
"writing, software # distributed under the License is distributed on",
"in writing, software # distributed under the License is distributed",
"# # Copyright 2014 The Oppia Authors. All Rights Reserved.",
"a customization arg specification.\"\"\" def __init__(self, name, description, schema, default_value):",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"utf-8 # # Copyright 2014 The Oppia Authors. All Rights",
"limitations under the License. \"\"\"Domain objects used within multiple extensions.\"\"\"",
"use this file except in compliance with the License. #",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"within multiple extensions.\"\"\" from __future__ import absolute_import # pylint: disable=import-only-modules",
"under the License is distributed on an \"AS-IS\" BASIS, #",
"default_value): self.name = name self.description = description self.schema = schema",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"__init__(self, name, description, schema, default_value): self.name = name self.description =",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"Oppia Authors. All Rights Reserved. # # Licensed under the",
"on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"absolute_import # pylint: disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object",
"or implied. # See the License for the specific language",
"Rights Reserved. # # Licensed under the Apache License, Version",
"License. # You may obtain a copy of the License",
"multiple extensions.\"\"\" from __future__ import absolute_import # pylint: disable=import-only-modules import",
"License, Version 2.0 (the \"License\"); # you may not use",
"name, description, schema, default_value): self.name = name self.description = description",
"= name self.description = description self.schema = schema self.default_value =",
"# You may obtain a copy of the License at",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"extensions.\"\"\" from __future__ import absolute_import # pylint: disable=import-only-modules import python_utils",
"Authors. All Rights Reserved. # # Licensed under the Apache",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"__future__ import absolute_import # pylint: disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT):",
"Reserved. # # Licensed under the Apache License, Version 2.0",
"and # limitations under the License. \"\"\"Domain objects used within",
"specification.\"\"\" def __init__(self, name, description, schema, default_value): self.name = name",
"the License. \"\"\"Domain objects used within multiple extensions.\"\"\" from __future__",
"the License for the specific language governing permissions and #",
"(the \"License\"); # you may not use this file except",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"# you may not use this file except in compliance",
"either express or implied. # See the License for the",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"distributed under the License is distributed on an \"AS-IS\" BASIS,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"permissions and # limitations under the License. \"\"\"Domain objects used",
"objects used within multiple extensions.\"\"\" from __future__ import absolute_import #",
"in compliance with the License. # You may obtain a",
"software # distributed under the License is distributed on an",
"CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a customization arg specification.\"\"\" def __init__(self,",
"\"\"\"Domain objects used within multiple extensions.\"\"\" from __future__ import absolute_import",
"# # Unless required by applicable law or agreed to",
"for a customization arg specification.\"\"\" def __init__(self, name, description, schema,",
"distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"name self.description = description self.schema = schema self.default_value = default_value",
"coding: utf-8 # # Copyright 2014 The Oppia Authors. All",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"Version 2.0 (the \"License\"); # you may not use this",
"disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a customization",
"law or agreed to in writing, software # distributed under",
"# distributed under the License is distributed on an \"AS-IS\"",
"an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"implied. # See the License for the specific language governing",
"is distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES OR",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"\"\"\"Value object for a customization arg specification.\"\"\" def __init__(self, name,",
"\"License\"); # you may not use this file except in",
"import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a customization arg",
"2014 The Oppia Authors. All Rights Reserved. # # Licensed",
"from __future__ import absolute_import # pylint: disable=import-only-modules import python_utils class",
"pylint: disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a",
"schema, default_value): self.name = name self.description = description self.schema =",
"by applicable law or agreed to in writing, software #",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"description, schema, default_value): self.name = name self.description = description self.schema",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"# See the License for the specific language governing permissions",
"object for a customization arg specification.\"\"\" def __init__(self, name, description,",
"You may obtain a copy of the License at #",
"governing permissions and # limitations under the License. \"\"\"Domain objects",
"License. \"\"\"Domain objects used within multiple extensions.\"\"\" from __future__ import",
"arg specification.\"\"\" def __init__(self, name, description, schema, default_value): self.name =",
"self.name = name self.description = description self.schema = schema self.default_value",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"language governing permissions and # limitations under the License. \"\"\"Domain",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"with the License. # You may obtain a copy of",
"this file except in compliance with the License. # You",
"used within multiple extensions.\"\"\" from __future__ import absolute_import # pylint:",
"License is distributed on an \"AS-IS\" BASIS, # WITHOUT WARRANTIES",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"customization arg specification.\"\"\" def __init__(self, name, description, schema, default_value): self.name",
"python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for a customization arg specification.\"\"\"",
"# pylint: disable=import-only-modules import python_utils class CustomizationArgSpec(python_utils.OBJECT): \"\"\"Value object for"
] |
[
"object_privileges: description: - List of ObjectPrivilege resources returned: on success",
"for this module.\") resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\",",
"\"object\": \"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\": \"YES\" }] \"\"\"",
"on the object. returned: on success type: str sample: name_example",
"on success type: str sample: schema_type_example owner: description: - The",
"OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK =",
"def list_resources(self): optional_list_method_params = [ \"name\", \"sort_by\", \"sort_order\", ] optional_kwargs",
"Infrastructure description: - Fetches details about one or multiple ObjectPrivilege",
"str sort_by: description: - The field to sort information by.",
"including tables, packages, indexes, sequences, and so on. returned: on",
"on success type: str sample: name_example schema_type: description: - The",
"NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__",
"YES inherited: description: - Indicates whether the role grant was",
"on success type: complex contains: name: description: - The name",
"license. # GNU General Public License v3.0+ (see COPYING or",
"type: str sample: YES common: description: - \"Indicates how the",
"module.fail_json(msg=\"oci python sdk required for this module.\") resource_facts_helper = ResourceFactsHelper(",
"object. returned: on success type: str sample: schema_type_example owner: description:",
"= ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result = []",
"- \"Indicates how the grant was made. Possible values: YES",
"# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)",
"dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\",",
"except ImportError: HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\"",
"resources in Oracle Cloud Infrastructure - Gets the list of",
"name_example schema_type: description: - The type of the object. returned:",
"whether the privilege was granted with the GRANT OPTION (YES)",
"Apache License v2.0 # See LICENSE.TXT for details. # GENERATED",
"match the entire name. type: str sort_by: description: - The",
"- A filter to return only resources that match the",
"descending ('DESC') order. Ascending order is the default order. type:",
"python sdk required for this module.\") resource_facts_helper = ResourceFactsHelper( module=module,",
"\"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\", ]",
"The object can be any object, including tables, packages, indexes,",
"- The field to sort information by. Only one sortOrder",
"from another container (YES) or not (NO) returned: on success",
"optional_kwargs = dict( (param, self.module.params[param]) for param in optional_list_method_params if",
"(CONTAINER=ALL was used) NO if the role was granted locally",
"param in optional_list_method_params if self.module.params.get(param) is not None ) return",
"('DESC') order. Ascending order is the default order. type: str",
"str sample: grantor_example hierarchy: description: - Indicates whether the privilege",
"used. The default sort order for 'NAME' is ascending. The",
"Fetches details about one or multiple ObjectPrivilege resources in Oracle",
"object. The object can be any object, including tables, packages,",
"object can be any object, including tables, packages, indexes, sequences,",
"v2.0 # See LICENSE.TXT for details. # GENERATED FILE -",
"GPL 3.0 license or the Apache 2.0 license. # GNU",
"(c) 2020, 2022 Oracle and/or its affiliates. # This software",
"\"supported_by\": \"community\", } DOCUMENTATION = \"\"\" --- module: oci_database_management_object_privilege_facts short_description:",
"\"2.9.0\" author: Oracle (@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm)",
"of the GPL 3.0 license or the Apache 2.0 license.",
"\"YES\", \"inherited\": \"YES\" }] \"\"\" from ansible.module_utils.basic import AnsibleModule from",
"sort information by. Only one sortOrder can be used. The",
"= [] if resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result)",
"not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required for this module.\") resource_facts_helper",
"and/or its affiliates. # This software is made available to",
"absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = { \"metadata_version\":",
"Indicates whether the privilege was granted with the GRANT OPTION",
"the Managed Database. type: str required: true user_name: description: -",
"grant_option: description: - Indicates whether the privilege was granted with",
"success type: str sample: YES common: description: - \"Indicates how",
"\"\"\" object_privileges: description: - List of ObjectPrivilege resources returned: on",
"\"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\":",
"NAME sort_order: ASC \"\"\" RETURN = \"\"\" object_privileges: description: -",
"details are to be viewed. type: str required: true name:",
"HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self):",
"HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required for this module.\") resource_facts_helper =",
"the privilege was granted with the GRANT OPTION (YES) or",
"ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result = [] if",
"\"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\": \"YES\"",
"required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) ) module",
"only resources that match the entire name. type: str sort_by:",
"this module.\") resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", )",
"type: str sample: YES object: description: - The name of",
"# optional name: name_example sort_by: NAME sort_order: ASC \"\"\" RETURN",
"- List of ObjectPrivilege resources returned: on success type: complex",
"\"\"\" --- module: oci_database_management_object_privilege_facts short_description: Fetches details about one or",
"str sample: YES inherited: description: - Indicates whether the role",
"= [ \"name\", \"sort_by\", \"sort_order\", ] optional_kwargs = dict( (param,",
"type: complex contains: name: description: - The name of the",
"] \"\"\" EXAMPLES = \"\"\" - name: List object_privileges oci_database_management_object_privilege_facts:",
"description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str",
"sort order is case-sensitive. type: str choices: - \"NAME\" sort_order:",
"resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result) if __name__ ==",
"list of Object Privileges granted for the specified user. version_added:",
"\"YES\", \"common\": \"YES\", \"inherited\": \"YES\" }] \"\"\" from ansible.module_utils.basic import",
"The owner of the object. returned: on success type: str",
"managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]),",
"ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def",
"choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) ) module = AnsibleModule(argument_spec=module_args) if",
"the list of Object Privileges granted for the specified user.",
"required for this module.\") resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient,",
"user_name: user_name_example # optional name: name_example sort_by: NAME sort_order: ASC",
"# This software is made available to you under the",
"DOCUMENTATION = \"\"\" --- module: oci_database_management_object_privilege_facts short_description: Fetches details about",
"\"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\",",
"\"name\", \"sort_by\", \"sort_order\", ] optional_kwargs = dict( (param, self.module.params[param]) for",
"[ \"name\", \"sort_by\", \"sort_order\", ] optional_kwargs = dict( (param, self.module.params[param])",
"<reponame>LaudateCorpus1/oci-ansible-collection #!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its",
"description: - Fetches details about one or multiple ObjectPrivilege resources",
"one sortOrder can be used. The default sort order for",
"of the object. returned: on success type: str sample: owner_example",
"(NO) returned: on success type: str sample: YES common: description:",
"import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {",
"str sample: owner_example grantor: description: - The name of the",
"resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result = [] if resource_facts_helper.is_list(): result",
"- The name of the privilege on the object. returned:",
"the entire name. type: str sort_by: description: - The field",
"L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str required: true user_name:",
"on success type: str sample: owner_example grantor: description: - The",
"- DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN",
"= AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required for",
"description: - A filter to return only resources that match",
"\"sort_by\", \"sort_order\", ] optional_kwargs = dict( (param, self.module.params[param]) for param",
"The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str required: true",
"description: - Indicates whether the privilege was granted with the",
"oci_database_management_object_privilege_facts short_description: Fetches details about one or multiple ObjectPrivilege resources",
"privilege was granted with the HIERARCHY OPTION (YES) or not",
"be used. The default sort order for 'NAME' is ascending.",
"\"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\",",
"\"status\": [\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION = \"\"\" --- module:",
"grantor_example hierarchy: description: - Indicates whether the privilege was granted",
"success type: str sample: grantor_example hierarchy: description: - Indicates whether",
"success type: str sample: object_example grant_option: description: - Indicates whether",
"under the terms of the GPL 3.0 license or the",
"= get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def main():",
"object. returned: on success type: str sample: name_example schema_type: description:",
"\"ASC\" - \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\" EXAMPLES =",
"whose details are to be viewed. type: str required: true",
"operations: list\"\"\" def get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\", ] def",
"LICENSE.TXT for details. # GENERATED FILE - DO NOT EDIT",
"description: - The name of the user who performed the",
"order for 'NAME' is ascending. The 'NAME' sort order is",
"ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import",
"class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def main(): module_args =",
"type: str sample: grantor_example hierarchy: description: - Indicates whether the",
"on. returned: on success type: str sample: object_example grant_option: description:",
"= True except ImportError: HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported",
"self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper(",
"WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__",
"owner: description: - The owner of the object. returned: on",
"if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required for this module.\")",
"dict( (param, self.module.params[param]) for param in optional_list_method_params if self.module.params.get(param) is",
"\"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\",",
"] optional_kwargs = dict( (param, self.module.params[param]) for param in optional_list_method_params",
"type: str choices: - \"NAME\" sort_order: description: - The option",
"viewed. type: str required: true name: description: - A filter",
"privilege was granted with the GRANT OPTION (YES) or not",
"grant was inherited from another container (YES) or not (NO)",
"description: - Indicates whether the role grant was inherited from",
"The name of the user who performed the grant returned:",
"\"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\": \"YES\" }] \"\"\" from ansible.module_utils.basic",
"in ascending ('ASC') or descending ('DESC') order. Ascending order is",
"import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try:",
"specified user. version_added: \"2.9.0\" author: Oracle (@oracle) options: managed_database_id: description:",
"was inherited from another container (YES) or not (NO) returned:",
"\"sort_order\", ] optional_kwargs = dict( (param, self.module.params[param]) for param in",
"success type: str sample: schema_type_example owner: description: - The owner",
"2022 Oracle and/or its affiliates. # This software is made",
"of the privilege on the object. returned: on success type:",
"class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self): return [ \"managed_database_id\",",
"indexes, sequences, and so on. returned: on success type: str",
"multiple ObjectPrivilege resources in Oracle Cloud Infrastructure - Gets the",
"sdk required for this module.\") resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\",",
"MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division,",
"YES if the role was granted commonly (CONTAINER=ALL was used)",
"on success type: str sample: YES object: description: - The",
"\"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION = \"\"\" ---",
"information in ascending ('ASC') or descending ('DESC') order. Ascending order",
"- Indicates whether the privilege was granted with the HIERARCHY",
"= { \"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION",
"not None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs )",
"description: - The field to sort information by. Only one",
"Privileges granted for the specified user. version_added: \"2.9.0\" author: Oracle",
"success type: str sample: name_example schema_type: description: - The type",
"common: description: - \"Indicates how the grant was made. Possible",
"CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import, division, print_function",
"str sample: schema_type_example owner: description: - The owner of the",
"NO if the role was granted locally (CONTAINER=ALL was not",
"2020, 2022 Oracle and/or its affiliates. # This software is",
"\"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\": \"YES\" }]",
"( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK",
"sample: object_example grant_option: description: - Indicates whether the privilege was",
"hierarchy: description: - Indicates whether the privilege was granted with",
"List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example #",
"or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for",
"- name: List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name:",
"v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 #",
"of ObjectPrivilege resources returned: on success type: complex contains: name:",
"= False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self): return",
"required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), )",
"return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\")",
"OPTION (YES) or not (NO) returned: on success type: str",
"so on. returned: on success type: str sample: object_example grant_option:",
"def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\",",
"= \"\"\" object_privileges: description: - List of ObjectPrivilege resources returned:",
"the grant was made. Possible values: YES if the role",
"for the specified user. version_added: \"2.9.0\" author: Oracle (@oracle) options:",
"from oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK",
"The 'NAME' sort order is case-sensitive. type: str choices: -",
"the role grant was inherited from another container (YES) or",
"True except ImportError: HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations:",
"\"user_name\", ] def list_resources(self): optional_list_method_params = [ \"name\", \"sort_by\", \"sort_order\",",
"get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def main(): module_args",
"are to be viewed. type: str required: true name: description:",
"user whose details are to be viewed. type: str required:",
"options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database.",
"sample: [{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\",",
"information by. Only one sortOrder can be used. The default",
"name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) ) module =",
"complex contains: name: description: - The name of the privilege",
"\"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\":",
"affiliates. # This software is made available to you under",
"resources returned: on success type: complex contains: name: description: -",
"description: - The owner of the object. returned: on success",
"[\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION = \"\"\" --- module: oci_database_management_object_privilege_facts",
"str choices: - \"ASC\" - \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ]",
"- \"NAME\" sort_order: description: - The option to sort information",
"- The name of the user whose details are to",
"granted locally (CONTAINER=ALL was not used)\" returned: on success type:",
"(CONTAINER=ALL was not used)\" returned: on success type: str sample:",
"import DbManagementClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False",
") module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk",
"Oracle (@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the",
"the HIERARCHY OPTION (YES) or not (NO) returned: on success",
"ObjectPrivilegeFactsHelperGen ): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict(",
"sortOrder can be used. The default sort order for 'NAME'",
"on success type: str sample: grantor_example hierarchy: description: - Indicates",
"of Object Privileges granted for the specified user. version_added: \"2.9.0\"",
"details about one or multiple ObjectPrivilege resources in Oracle Cloud",
") ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass",
"- The name of the user who performed the grant",
"role was granted commonly (CONTAINER=ALL was used) NO if the",
"granted for the specified user. version_added: \"2.9.0\" author: Oracle (@oracle)",
"to be viewed. type: str required: true name: description: -",
"order is the default order. type: str choices: - \"ASC\"",
"success type: str sample: YES inherited: description: - Indicates whether",
"its affiliates. # This software is made available to you",
"ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import",
"not (NO) returned: on success type: str sample: YES object:",
"for details. # GENERATED FILE - DO NOT EDIT -",
"ObjectPrivilege resources returned: on success type: complex contains: name: description:",
"values: YES if the role was granted commonly (CONTAINER=ALL was",
"name: name_example sort_by: NAME sort_order: ASC \"\"\" RETURN = \"\"\"",
"commonly (CONTAINER=ALL was used) NO if the role was granted",
"used)\" returned: on success type: str sample: YES inherited: description:",
"to sort information in ascending ('ASC') or descending ('DESC') order.",
"packages, indexes, sequences, and so on. returned: on success type:",
"FILE - DO NOT EDIT - MANUAL CHANGES WILL BE",
"- The type of the object. returned: on success type:",
"the grant returned: on success type: str sample: grantor_example hierarchy:",
"name of the user who performed the grant returned: on",
"option to sort information in ascending ('ASC') or descending ('DESC')",
"performed the grant returned: on success type: str sample: grantor_example",
"{ \"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION =",
"List of ObjectPrivilege resources returned: on success type: complex contains:",
"\"community\", } DOCUMENTATION = \"\"\" --- module: oci_database_management_object_privilege_facts short_description: Fetches",
"default sort order for 'NAME' is ascending. The 'NAME' sort",
"type: str sample: name_example schema_type: description: - The type of",
"\"\"\" - name: List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\"",
"- The owner of the object. returned: on success type:",
"ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update(",
"whether the role grant was inherited from another container (YES)",
"sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) ) module = AnsibleModule(argument_spec=module_args)",
"\"common\": \"YES\", \"inherited\": \"YES\" }] \"\"\" from ansible.module_utils.basic import AnsibleModule",
"granted with the GRANT OPTION (YES) or not (NO) returned:",
"oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional name:",
"module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result = [] if resource_facts_helper.is_list():",
"with the GRANT OPTION (YES) or not (NO) returned: on",
"sample: owner_example grantor: description: - The name of the user",
"This software is made available to you under the terms",
"user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen",
"COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT",
"the privilege on the object. returned: on success type: str",
"try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True except ImportError:",
"description: - The option to sort information in ascending ('ASC')",
"used) NO if the role was granted locally (CONTAINER=ALL was",
"# See LICENSE.TXT for details. # GENERATED FILE - DO",
"ANSIBLE_METADATA = { \"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\", }",
"AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase,",
"default order. type: str choices: - \"ASC\" - \"DESC\" extends_documentation_fragment:",
"true name: description: - A filter to return only resources",
"module.\") resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result",
"managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional name: name_example sort_by: NAME",
"how the grant was made. Possible values: YES if the",
"required: true name: description: - A filter to return only",
"description: - The name of the object. The object can",
"is made available to you under the terms of the",
"description: - The name of the user whose details are",
"made. Possible values: YES if the role was granted commonly",
"The name of the object. The object can be any",
"you under the terms of the GPL 3.0 license or",
"on success type: str sample: YES inherited: description: - Indicates",
"ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, )",
"\"YES\" }] \"\"\" from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import",
"\"\"\" RETURN = \"\"\" object_privileges: description: - List of ObjectPrivilege",
"returned: on success type: str sample: YES common: description: -",
"not used)\" returned: on success type: str sample: YES inherited:",
"(NO) returned: on success type: str sample: YES sample: [{",
"the Apache 2.0 license. # GNU General Public License v3.0+",
"\"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\":",
"object. returned: on success type: str sample: owner_example grantor: description:",
"name. type: str sort_by: description: - The field to sort",
"returned: on success type: str sample: owner_example grantor: description: -",
"grant returned: on success type: str sample: grantor_example hierarchy: description:",
"[] if resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result) if",
"- MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import absolute_import,",
"one or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure -",
"the privilege was granted with the HIERARCHY OPTION (YES) or",
"if self.module.params.get(param) is not None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"),",
"oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]),",
"type: str sample: YES inherited: description: - Indicates whether the",
"the object. returned: on success type: str sample: owner_example grantor:",
"The type of the object. returned: on success type: str",
"with the HIERARCHY OPTION (YES) or not (NO) returned: on",
"- \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\" EXAMPLES = \"\"\"",
"sample: schema_type_example owner: description: - The owner of the object.",
"\"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\" EXAMPLES = \"\"\" -",
"for param in optional_list_method_params if self.module.params.get(param) is not None )",
"for 'NAME' is ascending. The 'NAME' sort order is case-sensitive.",
"OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ = type",
"RETURN = \"\"\" object_privileges: description: - List of ObjectPrivilege resources",
"= resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result) if __name__ == \"__main__\": main()",
"returned: on success type: complex contains: name: description: - The",
"import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import (",
"locally (CONTAINER=ALL was not used)\" returned: on success type: str",
"(YES) or not (NO) returned: on success type: str sample:",
"- The option to sort information in ascending ('ASC') or",
"Infrastructure - Gets the list of Object Privileges granted for",
"Copyright (c) 2020, 2022 Oracle and/or its affiliates. # This",
"General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache",
"was not used)\" returned: on success type: str sample: YES",
"get_custom_class, ) try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True",
"Object Privileges granted for the specified user. version_added: \"2.9.0\" author:",
"Indicates whether the privilege was granted with the HIERARCHY OPTION",
"sample: YES sample: [{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\",",
"name of the user whose details are to be viewed.",
"the object. returned: on success type: str sample: name_example schema_type:",
"Only one sortOrder can be used. The default sort order",
"sample: YES inherited: description: - Indicates whether the role grant",
"license or the Apache 2.0 license. # GNU General Public",
"AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required for this",
"sequences, and so on. returned: on success type: str sample:",
"(@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed",
"description: - List of ObjectPrivilege resources returned: on success type:",
"of the Managed Database. type: str required: true user_name: description:",
"to return only resources that match the entire name. type:",
"user who performed the grant returned: on success type: str",
"name: List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example",
"get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\", ] def list_resources(self): optional_list_method_params =",
"another container (YES) or not (NO) returned: on success type:",
"owner_example grantor: description: - The name of the user who",
"the object. returned: on success type: str sample: schema_type_example owner:",
"License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0",
"schema_type: description: - The type of the object. returned: on",
"result = [] if resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail()",
"- The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type: str required:",
"can be any object, including tables, packages, indexes, sequences, and",
"was granted with the GRANT OPTION (YES) or not (NO)",
"name of the privilege on the object. returned: on success",
"sort_by: NAME sort_order: ASC \"\"\" RETURN = \"\"\" object_privileges: description:",
"schema_type_example owner: description: - The owner of the object. returned:",
"the terms of the GPL 3.0 license or the Apache",
"on success type: str sample: YES sample: [{ \"name\": \"name_example\",",
"- The name of the object. The object can be",
"or descending ('DESC') order. Ascending order is the default order.",
"Oracle Cloud Infrastructure - Gets the list of Object Privileges",
"true user_name: description: - The name of the user whose",
"made available to you under the terms of the GPL",
"Database. type: str required: true user_name: description: - The name",
"returned: on success type: str sample: name_example schema_type: description: -",
"success type: str sample: YES sample: [{ \"name\": \"name_example\", \"schema_type\":",
"was used) NO if the role was granted locally (CONTAINER=ALL",
"str sample: object_example grant_option: description: - Indicates whether the privilege",
"HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase):",
"contains: name: description: - The name of the privilege on",
"\"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\", \"common\":",
"# required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional name: name_example",
"the specified user. version_added: \"2.9.0\" author: Oracle (@oracle) options: managed_database_id:",
"choices: - \"NAME\" sort_order: description: - The option to sort",
"'NAME' sort order is case-sensitive. type: str choices: - \"NAME\"",
"or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure - Gets",
"name: description: - A filter to return only resources that",
"name: description: - The name of the privilege on the",
"author: Oracle (@oracle) options: managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of",
"\"\"\" from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from",
"be any object, including tables, packages, indexes, sequences, and so",
"- \"ASC\" - \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\" EXAMPLES",
"[ \"managed_database_id\", \"user_name\", ] def list_resources(self): optional_list_method_params = [ \"name\",",
"grant was made. Possible values: YES if the role was",
"managed_database_id: description: - The L(OCID,https://docs.cloud.oracle.com/Content/General/Concepts/identifiers.htm) of the Managed Database. type:",
"success type: complex contains: name: description: - The name of",
"\"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\": \"YES\", \"object\": \"object_example\", \"grant_option\": \"YES\",",
"self.module.params[param]) for param in optional_list_method_params if self.module.params.get(param) is not None",
"Indicates whether the role grant was inherited from another container",
"required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional name: name_example sort_by:",
"description: - The name of the privilege on the object.",
"or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure description: -",
"user_name_example # optional name: name_example sort_by: NAME sort_order: ASC \"\"\"",
"that match the entire name. type: str sort_by: description: -",
"ImportError: HAS_OCI_PY_SDK = False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def",
"role was granted locally (CONTAINER=ALL was not used)\" returned: on",
"HIERARCHY OPTION (YES) or not (NO) returned: on success type:",
"\"managed_database_id\", \"user_name\", ] def list_resources(self): optional_list_method_params = [ \"name\", \"sort_by\",",
"inherited: description: - Indicates whether the role grant was inherited",
"choices: - \"ASC\" - \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\"",
"to you under the terms of the GPL 3.0 license",
"success type: str sample: owner_example grantor: description: - The name",
"from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management",
"import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from oci.database_management import DbManagementClient",
"who performed the grant returned: on success type: str sample:",
"resource_facts_helper = ResourceFactsHelper( module=module, resource_type=\"object_privilege\", service_client_class=DbManagementClient, namespace=\"database_management\", ) result =",
"str choices: - \"NAME\" sort_order: description: - The option to",
"user_name: description: - The name of the user whose details",
"and so on. returned: on success type: str sample: object_example",
"can be used. The default sort order for 'NAME' is",
"short_description: Fetches details about one or multiple ObjectPrivilege resources in",
"__future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA =",
"list_resources(self): optional_list_method_params = [ \"name\", \"sort_by\", \"sort_order\", ] optional_kwargs =",
"object_privileges oci_database_management_object_privilege_facts: # required managed_database_id: \"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional",
"sort_order: description: - The option to sort information in ascending",
"was granted commonly (CONTAINER=ALL was used) NO if the role",
"was granted with the HIERARCHY OPTION (YES) or not (NO)",
"(NO) returned: on success type: str sample: YES object: description:",
"returned: on success type: str sample: grantor_example hierarchy: description: -",
"object_example grant_option: description: - Indicates whether the privilege was granted",
"was made. Possible values: YES if the role was granted",
"resources that match the entire name. type: str sort_by: description:",
"}] \"\"\" from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils",
"user. version_added: \"2.9.0\" author: Oracle (@oracle) options: managed_database_id: description: -",
"returned: on success type: str sample: YES inherited: description: -",
"A filter to return only resources that match the entire",
"be viewed. type: str required: true name: description: - A",
"the user whose details are to be viewed. type: str",
"ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\",",
"any object, including tables, packages, indexes, sequences, and so on.",
"order. type: str choices: - \"ASC\" - \"DESC\" extends_documentation_fragment: [",
"sort_order: ASC \"\"\" RETURN = \"\"\" object_privileges: description: - List",
"inherited from another container (YES) or not (NO) returned: on",
"object, including tables, packages, indexes, sequences, and so on. returned:",
"3.0 license or the Apache 2.0 license. # GNU General",
"division, print_function __metaclass__ = type ANSIBLE_METADATA = { \"metadata_version\": \"1.1\",",
"(see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See",
"is not None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs",
"str required: true user_name: description: - The name of the",
"to sort information by. Only one sortOrder can be used.",
"Ascending order is the default order. type: str choices: -",
"The name of the user whose details are to be",
"self.module.params.get(param) is not None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"),",
"user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) )",
"= dict( (param, self.module.params[param]) for param in optional_list_method_params if self.module.params.get(param)",
"oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class, ) try: from",
"Gets the list of Object Privileges granted for the specified",
"ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ): pass def main(): module_args = oci_common_utils.get_common_arg_spec()",
"container (YES) or not (NO) returned: on success type: str",
"whether the privilege was granted with the HIERARCHY OPTION (YES)",
"sort order for 'NAME' is ascending. The 'NAME' sort order",
"case-sensitive. type: str choices: - \"NAME\" sort_order: description: - The",
"oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class",
"if the role was granted commonly (CONTAINER=ALL was used) NO",
"type: str sort_by: description: - The field to sort information",
"the default order. type: str choices: - \"ASC\" - \"DESC\"",
"= \"\"\" - name: List object_privileges oci_database_management_object_privilege_facts: # required managed_database_id:",
"the role was granted locally (CONTAINER=ALL was not used)\" returned:",
") result = [] if resource_facts_helper.is_list(): result = resource_facts_helper.list() else:",
"the GPL 3.0 license or the Apache 2.0 license. #",
"managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom,",
"type: str required: true user_name: description: - The name of",
"optional_list_method_params = [ \"name\", \"sort_by\", \"sort_order\", ] optional_kwargs = dict(",
"= type ANSIBLE_METADATA = { \"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\":",
"of the object. The object can be any object, including",
"version_added: \"2.9.0\" author: Oracle (@oracle) options: managed_database_id: description: - The",
"('ASC') or descending ('DESC') order. Ascending order is the default",
"https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License v2.0 # See LICENSE.TXT for details.",
"if the role was granted locally (CONTAINER=ALL was not used)\"",
"from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils",
"not (NO) returned: on success type: str sample: YES common:",
"BE OVERWRITTEN from __future__ import absolute_import, division, print_function __metaclass__ =",
"The name of the privilege on the object. returned: on",
"grantor: description: - The name of the user who performed",
"] def list_resources(self): optional_list_method_params = [ \"name\", \"sort_by\", \"sort_order\", ]",
"YES sample: [{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\":",
"description: - \"Indicates how the grant was made. Possible values:",
"name_example sort_by: NAME sort_order: ASC \"\"\" RETURN = \"\"\" object_privileges:",
"[ oracle.oci.oracle ] \"\"\" EXAMPLES = \"\"\" - name: List",
"namespace=\"database_management\", ) result = [] if resource_facts_helper.is_list(): result = resource_facts_helper.list()",
"type of the object. returned: on success type: str sample:",
"Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) # Apache License",
"None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom",
"was granted locally (CONTAINER=ALL was not used)\" returned: on success",
"in optional_list_method_params if self.module.params.get(param) is not None ) return oci_common_utils.list_all_resources(",
"returned: on success type: str sample: YES object: description: -",
"tables, packages, indexes, sequences, and so on. returned: on success",
"if resource_facts_helper.is_list(): result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result) if __name__",
"Oracle Cloud Infrastructure description: - Fetches details about one or",
"in Oracle Cloud Infrastructure - Gets the list of Object",
"module: oci_database_management_object_privilege_facts short_description: Fetches details about one or multiple ObjectPrivilege",
"str required: true name: description: - A filter to return",
"def get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\", ] def list_resources(self): optional_list_method_params",
"Managed Database. type: str required: true user_name: description: - The",
"filter to return only resources that match the entire name.",
"type ANSIBLE_METADATA = { \"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\",",
"by. Only one sortOrder can be used. The default sort",
"about one or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure",
") try: from oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True except",
"sort information in ascending ('ASC') or descending ('DESC') order. Ascending",
"GENERATED FILE - DO NOT EDIT - MANUAL CHANGES WILL",
"EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from __future__ import",
"the object. The object can be any object, including tables,",
"choices=[\"ASC\", \"DESC\"]), ) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK:",
"False class ObjectPrivilegeFactsHelperGen(OCIResourceFactsHelperBase): \"\"\"Supported operations: list\"\"\" def get_required_params_for_list(self): return [",
"GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) #",
"returned: on success type: str sample: object_example grant_option: description: -",
"'NAME' is ascending. The 'NAME' sort order is case-sensitive. type:",
"2.0 license. # GNU General Public License v3.0+ (see COPYING",
"License v2.0 # See LICENSE.TXT for details. # GENERATED FILE",
"The default sort order for 'NAME' is ascending. The 'NAME'",
"\"ocid1.manageddatabase.oc1..xxxxxxEXAMPLExxxxxx\" user_name: user_name_example # optional name: name_example sort_by: NAME sort_order:",
"role grant was inherited from another container (YES) or not",
"module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"),",
"result = resource_facts_helper.list() else: resource_facts_helper.fail() module.exit_json(object_privileges=result) if __name__ == \"__main__\":",
"): pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\",",
"- Indicates whether the role grant was inherited from another",
"available to you under the terms of the GPL 3.0",
"--- module: oci_database_management_object_privilege_facts short_description: Fetches details about one or multiple",
"order is case-sensitive. type: str choices: - \"NAME\" sort_order: description:",
"or not (NO) returned: on success type: str sample: YES",
"one or multiple ObjectPrivilege resources in Oracle Cloud Infrastructure description:",
"ObjectPrivilege resources in Oracle Cloud Infrastructure description: - Fetches details",
"YES common: description: - \"Indicates how the grant was made.",
"\"Indicates how the grant was made. Possible values: YES if",
"from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA",
"type: str sample: schema_type_example owner: description: - The owner of",
"the role was granted commonly (CONTAINER=ALL was used) NO if",
"required: true user_name: description: - The name of the user",
"} DOCUMENTATION = \"\"\" --- module: oci_database_management_object_privilege_facts short_description: Fetches details",
"#!/usr/bin/python # Copyright (c) 2020, 2022 Oracle and/or its affiliates.",
"print_function __metaclass__ = type ANSIBLE_METADATA = { \"metadata_version\": \"1.1\", \"status\":",
"ascending. The 'NAME' sort order is case-sensitive. type: str choices:",
"sample: YES object: description: - The name of the object.",
"EXAMPLES = \"\"\" - name: List object_privileges oci_database_management_object_privilege_facts: # required",
"\"metadata_version\": \"1.1\", \"status\": [\"preview\"], \"supported_by\": \"community\", } DOCUMENTATION = \"\"\"",
"success type: str sample: YES object: description: - The name",
"ObjectPrivilege resources in Oracle Cloud Infrastructure - Gets the list",
") ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python",
"# GENERATED FILE - DO NOT EDIT - MANUAL CHANGES",
"entire name. type: str sort_by: description: - The field to",
"on success type: str sample: YES common: description: - \"Indicates",
"= oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\",",
"owner of the object. returned: on success type: str sample:",
"granted with the HIERARCHY OPTION (YES) or not (NO) returned:",
"sample: YES common: description: - \"Indicates how the grant was",
"sample: grantor_example hierarchy: description: - Indicates whether the privilege was",
"type: str required: true name: description: - A filter to",
"module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci python sdk required",
"is case-sensitive. type: str choices: - \"NAME\" sort_order: description: -",
"(param, self.module.params[param]) for param in optional_list_method_params if self.module.params.get(param) is not",
"object: description: - The name of the object. The object",
"str sample: YES sample: [{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\":",
"terms of the GPL 3.0 license or the Apache 2.0",
"# Apache License v2.0 # See LICENSE.TXT for details. #",
"of the object. returned: on success type: str sample: schema_type_example",
"is ascending. The 'NAME' sort order is case-sensitive. type: str",
"sort_order=dict(type=\"str\", choices=[\"ASC\", \"DESC\"]), ) ) module = AnsibleModule(argument_spec=module_args) if not",
"granted commonly (CONTAINER=ALL was used) NO if the role was",
"pass def main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True),",
"str sample: YES common: description: - \"Indicates how the grant",
"description: - The type of the object. returned: on success",
"oracle.oci.oracle ] \"\"\" EXAMPLES = \"\"\" - name: List object_privileges",
"DbManagementClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK = False class",
"service_client_class=DbManagementClient, namespace=\"database_management\", ) result = [] if resource_facts_helper.is_list(): result =",
"**optional_kwargs ) ObjectPrivilegeFactsHelperCustom = get_custom_class(\"ObjectPrivilegeFactsHelperCustom\") class ResourceFactsHelper( ObjectPrivilegeFactsHelperCustom, ObjectPrivilegeFactsHelperGen ):",
"\"NAME\" sort_order: description: - The option to sort information in",
"returned: on success type: str sample: YES sample: [{ \"name\":",
"order. Ascending order is the default order. type: str choices:",
"# Copyright (c) 2020, 2022 Oracle and/or its affiliates. #",
"the user who performed the grant returned: on success type:",
"GRANT OPTION (YES) or not (NO) returned: on success type:",
"DO NOT EDIT - MANUAL CHANGES WILL BE OVERWRITTEN from",
"resources in Oracle Cloud Infrastructure description: - Fetches details about",
"not (NO) returned: on success type: str sample: YES sample:",
"privilege on the object. returned: on success type: str sample:",
"type: str sample: YES sample: [{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\",",
") return oci_common_utils.list_all_resources( self.client.list_object_privileges, managed_database_id=self.module.params.get(\"managed_database_id\"), user_name=self.module.params.get(\"user_name\"), **optional_kwargs ) ObjectPrivilegeFactsHelperCustom =",
"type: str sample: owner_example grantor: description: - The name of",
"from ansible_collections.oracle.oci.plugins.module_utils import oci_common_utils from ansible_collections.oracle.oci.plugins.module_utils.oci_resource_utils import ( OCIResourceFactsHelperBase, get_custom_class,",
"is the default order. type: str choices: - \"ASC\" -",
"the GRANT OPTION (YES) or not (NO) returned: on success",
"Apache 2.0 license. # GNU General Public License v3.0+ (see",
"optional_list_method_params if self.module.params.get(param) is not None ) return oci_common_utils.list_all_resources( self.client.list_object_privileges,",
"= \"\"\" --- module: oci_database_management_object_privilege_facts short_description: Fetches details about one",
"oci.database_management import DbManagementClient HAS_OCI_PY_SDK = True except ImportError: HAS_OCI_PY_SDK =",
"str sample: YES object: description: - The name of the",
"- Gets the list of Object Privileges granted for the",
"main(): module_args = oci_common_utils.get_common_arg_spec() module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True),",
"str sample: name_example schema_type: description: - The type of the",
"See LICENSE.TXT for details. # GENERATED FILE - DO NOT",
"\"object_example\", \"grant_option\": \"YES\", \"common\": \"YES\", \"inherited\": \"YES\" }] \"\"\" from",
"field to sort information by. Only one sortOrder can be",
"software is made available to you under the terms of",
"module_args.update( dict( managed_database_id=dict(type=\"str\", required=True), user_name=dict(type=\"str\", required=True), name=dict(type=\"str\"), sort_by=dict(type=\"str\", choices=[\"NAME\"]), sort_order=dict(type=\"str\",",
"ASC \"\"\" RETURN = \"\"\" object_privileges: description: - List of",
"\"DESC\"]), ) ) module = AnsibleModule(argument_spec=module_args) if not HAS_OCI_PY_SDK: module.fail_json(msg=\"oci",
"Oracle and/or its affiliates. # This software is made available",
"Possible values: YES if the role was granted commonly (CONTAINER=ALL",
"of the user whose details are to be viewed. type:",
"- Fetches details about one or multiple ObjectPrivilege resources in",
"YES object: description: - The name of the object. The",
"Cloud Infrastructure - Gets the list of Object Privileges granted",
"sort_by: description: - The field to sort information by. Only",
"- Indicates whether the privilege was granted with the GRANT",
"The field to sort information by. Only one sortOrder can",
"sample: name_example schema_type: description: - The type of the object.",
"list\"\"\" def get_required_params_for_list(self): return [ \"managed_database_id\", \"user_name\", ] def list_resources(self):",
"\"\"\" EXAMPLES = \"\"\" - name: List object_privileges oci_database_management_object_privilege_facts: #",
"of the user who performed the grant returned: on success",
"Cloud Infrastructure description: - Fetches details about one or multiple",
"in Oracle Cloud Infrastructure description: - Fetches details about one",
"ascending ('ASC') or descending ('DESC') order. Ascending order is the",
"The option to sort information in ascending ('ASC') or descending",
"details. # GENERATED FILE - DO NOT EDIT - MANUAL",
"on success type: str sample: object_example grant_option: description: - Indicates",
"or the Apache 2.0 license. # GNU General Public License",
"optional name: name_example sort_by: NAME sort_order: ASC \"\"\" RETURN =",
"returned: on success type: str sample: schema_type_example owner: description: -",
"return [ \"managed_database_id\", \"user_name\", ] def list_resources(self): optional_list_method_params = [",
"type: str choices: - \"ASC\" - \"DESC\" extends_documentation_fragment: [ oracle.oci.oracle",
"return only resources that match the entire name. type: str",
"__metaclass__ = type ANSIBLE_METADATA = { \"metadata_version\": \"1.1\", \"status\": [\"preview\"],",
"\"inherited\": \"YES\" }] \"\"\" from ansible.module_utils.basic import AnsibleModule from ansible_collections.oracle.oci.plugins.module_utils",
"[{ \"name\": \"name_example\", \"schema_type\": \"schema_type_example\", \"owner\": \"owner_example\", \"grantor\": \"grantor_example\", \"hierarchy\":",
"name of the object. The object can be any object,",
"multiple ObjectPrivilege resources in Oracle Cloud Infrastructure description: - Fetches",
"extends_documentation_fragment: [ oracle.oci.oracle ] \"\"\" EXAMPLES = \"\"\" - name:",
"type: str sample: object_example grant_option: description: - Indicates whether the"
] |
[
"are available for Numba >= 0.55 int32_t = ir.IntType(32) def",
"available for Numba >= 0.55 int32_t = ir.IntType(32) def cg_fflush(builder):",
"target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return sig, codegen else: raise",
".. note:: ``fflush`` is available only for CPU target. \"\"\"",
"= ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)])",
"rbc import irutils from llvmlite import ir from rbc.targetinfo import",
"irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that",
"\"\"\" sig = nb_types.void(nb_types.void) def codegen(context, builder, signature, args): target_info",
"= ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty,",
"NumbaTypeError # some errors are available for Numba >= 0.55",
"``fflush`` is available only for CPU target. \"\"\" sig =",
".. note:: ``printf`` is available only for CPU target. \"\"\"",
"fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx):",
"Numba jit-decorated functions. .. note:: ``printf`` is available only for",
"from rbc.targetinfo import TargetInfo from numba.core import cgutils, extending from",
"format_type, *args): \"\"\"``printf`` that can be called from Numba jit-decorated",
"nb_types.void(nb_types.void) def codegen(context, builder, signature, args): target_info = TargetInfo() if",
"args): target_info = TargetInfo() if target_info.is_cpu: cg_fflush(builder) return sig, codegen",
"printf(typingctx, format_type, *args): \"\"\"``printf`` that can be called from Numba",
"from rbc.errors import NumbaTypeError # some errors are available for",
"available only for CPU target. \"\"\" if isinstance(format_type, nb_types.StringLiteral): sig",
"target_info = TargetInfo() if target_info.is_cpu: cg_fflush(builder) return sig, codegen @extending.intrinsic",
"TargetInfo() if target_info.is_cpu: cg_fflush(builder) return sig, codegen @extending.intrinsic def printf(typingctx,",
"*args): \"\"\"``printf`` that can be called from Numba jit-decorated functions.",
"format_type.literal_value, *args[1:]) cg_fflush(builder) return sig, codegen else: raise NumbaTypeError(f\"expected StringLiteral",
"codegen(context, builder, signature, args): target_info = TargetInfo() if target_info.is_cpu: cgutils.printf(builder,",
"cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return sig, codegen else: raise NumbaTypeError(f\"expected",
"functions. .. note:: ``printf`` is available only for CPU target.",
"can be called from Numba jit-decorated functions. .. note:: ``printf``",
"@extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that can be called from Numba",
"functions. .. note:: ``fflush`` is available only for CPU target.",
"signature, args): target_info = TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:])",
"llvmlite import ir from rbc.targetinfo import TargetInfo from numba.core import",
"Numba jit-decorated functions. .. note:: ``fflush`` is available only for",
"be called from Numba jit-decorated functions. .. note:: ``fflush`` is",
"import types as nb_types from rbc.errors import NumbaTypeError # some",
"from numba.core import cgutils, extending from numba.core import types as",
"ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\")",
"called from Numba jit-decorated functions. .. note:: ``fflush`` is available",
"nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature, args): target_info = TargetInfo() if",
"codegen @extending.intrinsic def printf(typingctx, format_type, *args): \"\"\"``printf`` that can be",
"from numba.core import types as nb_types from rbc.errors import NumbaTypeError",
"= TargetInfo() if target_info.is_cpu: cg_fflush(builder) return sig, codegen @extending.intrinsic def",
"cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn =",
"if isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder,",
"import cgutils, extending from numba.core import types as nb_types from",
"def codegen(context, builder, signature, args): target_info = TargetInfo() if target_info.is_cpu:",
"note:: ``fflush`` is available only for CPU target. \"\"\" sig",
"return sig, codegen else: raise NumbaTypeError(f\"expected StringLiteral but got {type(format_type).__name__}\")",
"import irutils from llvmlite import ir from rbc.targetinfo import TargetInfo",
"ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic",
"[int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def",
"numba.core import types as nb_types from rbc.errors import NumbaTypeError #",
"= irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush``",
"signature, args): target_info = TargetInfo() if target_info.is_cpu: cg_fflush(builder) return sig,",
"name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that can be",
"import NumbaTypeError # some errors are available for Numba >=",
"is available only for CPU target. \"\"\" if isinstance(format_type, nb_types.StringLiteral):",
"cg_fflush(builder) return sig, codegen else: raise NumbaTypeError(f\"expected StringLiteral but got",
"\"\"\" from rbc import irutils from llvmlite import ir from",
"for CPU target. \"\"\" if isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type,",
"sig = nb_types.void(nb_types.void) def codegen(context, builder, signature, args): target_info =",
"as nb_types from rbc.errors import NumbaTypeError # some errors are",
"cgutils, extending from numba.core import types as nb_types from rbc.errors",
"nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature, args): target_info = TargetInfo()",
"jit-decorated functions. .. note:: ``fflush`` is available only for CPU",
"for CPU target. \"\"\" sig = nb_types.void(nb_types.void) def codegen(context, builder,",
"0.55 int32_t = ir.IntType(32) def cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty",
"only for CPU target. \"\"\" sig = nb_types.void(nb_types.void) def codegen(context,",
"rbc.errors import NumbaTypeError # some errors are available for Numba",
"from llvmlite import ir from rbc.targetinfo import TargetInfo from numba.core",
"from Numba jit-decorated functions. .. note:: ``fflush`` is available only",
"target_info = TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return",
"if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return sig, codegen else:",
"cg_fflush(builder) return sig, codegen @extending.intrinsic def printf(typingctx, format_type, *args): \"\"\"``printf``",
"sig, codegen @extending.intrinsic def printf(typingctx, format_type, *args): \"\"\"``printf`` that can",
"errors are available for Numba >= 0.55 int32_t = ir.IntType(32)",
"\"\"\"https://en.cppreference.com/w/c/io \"\"\" from rbc import irutils from llvmlite import ir",
"jit-decorated functions. .. note:: ``printf`` is available only for CPU",
"# some errors are available for Numba >= 0.55 int32_t",
"[int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that can be called from",
"that can be called from Numba jit-decorated functions. .. note::",
"ir.IntType(32) def cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()])",
"for Numba >= 0.55 int32_t = ir.IntType(32) def cg_fflush(builder): int8_t",
">= 0.55 int32_t = ir.IntType(32) def cg_fflush(builder): int8_t = ir.IntType(8)",
"codegen(context, builder, signature, args): target_info = TargetInfo() if target_info.is_cpu: cg_fflush(builder)",
"TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return sig, codegen",
"builder, signature, args): target_info = TargetInfo() if target_info.is_cpu: cg_fflush(builder) return",
"fflush(typingctx): \"\"\"``fflush`` that can be called from Numba jit-decorated functions.",
"\"\"\" if isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context,",
"note:: ``printf`` is available only for CPU target. \"\"\" if",
"TargetInfo from numba.core import cgutils, extending from numba.core import types",
"numba.core import cgutils, extending from numba.core import types as nb_types",
"isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature,",
"def fflush(typingctx): \"\"\"``fflush`` that can be called from Numba jit-decorated",
"some errors are available for Numba >= 0.55 int32_t =",
"types as nb_types from rbc.errors import NumbaTypeError # some errors",
"import TargetInfo from numba.core import cgutils, extending from numba.core import",
"can be called from Numba jit-decorated functions. .. note:: ``fflush``",
"Numba >= 0.55 int32_t = ir.IntType(32) def cg_fflush(builder): int8_t =",
"extending from numba.core import types as nb_types from rbc.errors import",
"be called from Numba jit-decorated functions. .. note:: ``printf`` is",
"= nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature, args): target_info =",
"import ir from rbc.targetinfo import TargetInfo from numba.core import cgutils,",
"args): target_info = TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder)",
"= ir.IntType(32) def cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t,",
"fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module, fflush_fnty, name=\"fflush\") builder.call(fflush_fn,",
"<reponame>guilhermeleobas/rbc \"\"\"https://en.cppreference.com/w/c/io \"\"\" from rbc import irutils from llvmlite import",
"int8_t = ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn = irutils.get_or_insert_function(builder.module,",
"is available only for CPU target. \"\"\" sig = nb_types.void(nb_types.void)",
"if target_info.is_cpu: cg_fflush(builder) return sig, codegen @extending.intrinsic def printf(typingctx, format_type,",
"= TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value, *args[1:]) cg_fflush(builder) return sig,",
"def cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty = ir.FunctionType(int32_t, [int8_t.as_pointer()]) fflush_fn",
"builder, signature, args): target_info = TargetInfo() if target_info.is_cpu: cgutils.printf(builder, format_type.literal_value,",
"target. \"\"\" if isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def",
"``printf`` is available only for CPU target. \"\"\" if isinstance(format_type,",
"CPU target. \"\"\" sig = nb_types.void(nb_types.void) def codegen(context, builder, signature,",
"nb_types from rbc.errors import NumbaTypeError # some errors are available",
"int32_t = ir.IntType(32) def cg_fflush(builder): int8_t = ir.IntType(8) fflush_fnty =",
"ir from rbc.targetinfo import TargetInfo from numba.core import cgutils, extending",
"target_info.is_cpu: cg_fflush(builder) return sig, codegen @extending.intrinsic def printf(typingctx, format_type, *args):",
"rbc.targetinfo import TargetInfo from numba.core import cgutils, extending from numba.core",
"\"\"\"``fflush`` that can be called from Numba jit-decorated functions. ..",
"= nb_types.void(nb_types.void) def codegen(context, builder, signature, args): target_info = TargetInfo()",
"only for CPU target. \"\"\" if isinstance(format_type, nb_types.StringLiteral): sig =",
"return sig, codegen @extending.intrinsic def printf(typingctx, format_type, *args): \"\"\"``printf`` that",
"sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature, args): target_info",
"builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that can be called",
"*args[1:]) cg_fflush(builder) return sig, codegen else: raise NumbaTypeError(f\"expected StringLiteral but",
"@extending.intrinsic def printf(typingctx, format_type, *args): \"\"\"``printf`` that can be called",
"from Numba jit-decorated functions. .. note:: ``printf`` is available only",
"def printf(typingctx, format_type, *args): \"\"\"``printf`` that can be called from",
"irutils from llvmlite import ir from rbc.targetinfo import TargetInfo from",
"fflush_fnty, name=\"fflush\") builder.call(fflush_fn, [int8_t.as_pointer()(None)]) @extending.intrinsic def fflush(typingctx): \"\"\"``fflush`` that can",
"available only for CPU target. \"\"\" sig = nb_types.void(nb_types.void) def",
"nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args)) def codegen(context, builder, signature, args):",
"\"\"\"``printf`` that can be called from Numba jit-decorated functions. ..",
"CPU target. \"\"\" if isinstance(format_type, nb_types.StringLiteral): sig = nb_types.void(format_type, nb_types.BaseTuple.from_types(args))",
"from rbc import irutils from llvmlite import ir from rbc.targetinfo",
"target. \"\"\" sig = nb_types.void(nb_types.void) def codegen(context, builder, signature, args):",
"called from Numba jit-decorated functions. .. note:: ``printf`` is available"
] |
[
"'Programming Language :: Python :: 3', 'Programming Language :: Python",
"encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of Hue",
"url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 4 -",
"MIT License', 'Programming Language :: Python :: 3', 'Programming Language",
"License', 'Programming Language :: Python :: 3', 'Programming Language ::",
"license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience",
"author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 4 - Beta',",
"'Programming Language :: Python :: 3.5', 'Programming Language :: Python",
":: 3.5', 'Programming Language :: Python :: 3.6', ], keywords='philips",
":: MIT License', 'Programming Language :: Python :: 3', 'Programming",
"long_description = codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto",
"except ImportError: import codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description =",
"Developers', 'License :: OSI Approved :: MIT License', 'Programming Language",
"3.5', 'Programming Language :: Python :: 3.6', ], keywords='philips hue',",
"= '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of Hue bridges', long_description=long_description,",
"Python :: 3', 'Programming Language :: Python :: 3.5', 'Programming",
"of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[",
"description='Auto discovery of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>',",
"'Intended Audience :: Developers', 'License :: OSI Approved :: MIT",
"3', 'Programming Language :: Python :: 3.5', 'Programming Language ::",
"Language :: Python :: 3.6', ], keywords='philips hue', packages=['discoverhue'], install_requires=['httpfind'],",
"'\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of Hue bridges', long_description=long_description, version='1.0.2',",
":: Developers', 'License :: OSI Approved :: MIT License', 'Programming",
"setup try: import pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except",
"= codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery",
"setup( name='discoverhue', description='Auto discovery of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue',",
"- Beta', 'Intended Audience :: Developers', 'License :: OSI Approved",
":: Python :: 3.6', ], keywords='philips hue', packages=['discoverhue'], install_requires=['httpfind'], )",
"= pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import codecs long_description =",
"classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience ::",
"ImportError: import codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines())",
"'License :: OSI Approved :: MIT License', 'Programming Language ::",
"OSI Approved :: MIT License', 'Programming Language :: Python ::",
"4 - Beta', 'Intended Audience :: Developers', 'License :: OSI",
"Status :: 4 - Beta', 'Intended Audience :: Developers', 'License",
"'rst', extra_args=()) except ImportError: import codecs long_description = codecs.open('README.md', encoding='utf-8').read()",
"Language :: Python :: 3.5', 'Programming Language :: Python ::",
"Language :: Python :: 3', 'Programming Language :: Python ::",
"Python :: 3.5', 'Programming Language :: Python :: 3.6', ],",
"import setup try: import pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=())",
"bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status",
":: 4 - Beta', 'Intended Audience :: Developers', 'License ::",
"name='discoverhue', description='Auto discovery of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard',",
"long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of Hue bridges',",
"Audience :: Developers', 'License :: OSI Approved :: MIT License',",
"extra_args=()) except ImportError: import codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description",
"codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue',",
"long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import codecs long_description",
"Approved :: MIT License', 'Programming Language :: Python :: 3',",
"try: import pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError:",
"discovery of Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT',",
":: OSI Approved :: MIT License', 'Programming Language :: Python",
":: Python :: 3.5', 'Programming Language :: Python :: 3.6',",
"import codecs long_description = codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup(",
"'Development Status :: 4 - Beta', 'Intended Audience :: Developers',",
"Beta', 'Intended Audience :: Developers', 'License :: OSI Approved ::",
"<gh_stars>1-10 from setuptools import setup try: import pypandoc long_description =",
":: Python :: 3', 'Programming Language :: Python :: 3.5',",
":: 3', 'Programming Language :: Python :: 3.5', 'Programming Language",
"long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status ::",
"author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 4 - Beta', 'Intended",
"'Programming Language :: Python :: 3.6', ], keywords='philips hue', packages=['discoverhue'],",
"import pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import",
"Hue bridges', long_description=long_description, version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development",
"pypandoc long_description = pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import codecs",
"pypandoc.convert_file('README.md', 'rst', extra_args=()) except ImportError: import codecs long_description = codecs.open('README.md',",
"codecs.open('README.md', encoding='utf-8').read() long_description = '\\n'.join(long_description.splitlines()) setup( name='discoverhue', description='Auto discovery of",
"version='1.0.2', url='https://github.com/Overboard/discoverhue', author='Overboard', author_email='<EMAIL>', license='MIT', classifiers=[ 'Development Status :: 4",
"setuptools import setup try: import pypandoc long_description = pypandoc.convert_file('README.md', 'rst',",
"from setuptools import setup try: import pypandoc long_description = pypandoc.convert_file('README.md',"
] |
[
"x_final = np.zeros(nframes * p.len2) aa = 0.98 mu =",
"(c) 2015 braindead # # Permission is hereby granted, free",
"# # # This code was extracted from the logmmse",
"np.zeros(n_fft) n_frames = len(noise) // window_size for j in range(0,",
"noise_mu2, 40) if xk_prev.all() == 0: ksi = aa +",
"axis=0) xi_w = np.real(xi_w) x_final[k:k + p.len2] = x_old +",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A",
"OTHER DEALINGS IN THE # SOFTWARE. # # # This",
"+ ksi) - np.log(1 + ksi) vad_decision = np.sum(log_sigma_k) /",
"OR OTHER DEALINGS IN THE # SOFTWARE. # # #",
"_input.dtype == np.int32: return _input / 2147483648., _input.dtype raise ValueError('Unsupported",
"numpy array of floats or ints. :param noise_profile: a NoiseProfile",
"x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2 for",
"of floats or ints of the same length. \"\"\" wav,",
"# # This code was extracted from the logmmse package",
"for j in range(0, window_size * n_frames, window_size): noise_mean +=",
"_input / 2147483648., _input.dtype raise ValueError('Unsupported wave file format') def",
"my needs. import numpy as np import math from scipy.special",
"np.log(1 + ksi) vad_decision = np.sum(log_sigma_k) / p.window_size if vad_decision",
"gammak * ksi/(1 + ksi) - np.log(1 + ksi) vad_decision",
"NoiseProfile object that was created from a similar (or a",
"window_size * n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j +",
"* ksi/(1 + ksi) - np.log(1 + ksi) vad_decision =",
"(1 + ksi) vk = a * gammak ei_vk =",
"expn(1, np.maximum(vk, 1e-8)) hw = a * np.exp(ei_vk) sig =",
"sig ** 2 gammak = np.minimum(sig2 / noise_mu2, 40) if",
"a * gammak ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8))",
"len(wav) - len(output)), mode=\"constant\") return output def to_float(_input): if _input.dtype",
"TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR",
"1, 0) ksi = np.maximum(ksi_min, ksi) log_sigma_k = gammak *",
"mode=\"constant\") return output def to_float(_input): if _input.dtype == np.float64: return",
"== np.float32: return _input.astype(np.float64), _input.dtype elif _input.dtype == np.uint8: return",
"rights # to use, copy, modify, merge, publish, distribute, sublicense,",
"numpy array of floats or ints. :param sampling_rate: the sampling",
"wav as a numpy array of floats or ints of",
"or ints. :param sampling_rate: the sampling rate of the audio",
"* window_size noise_mean = np.zeros(n_fft) n_frames = len(noise) // window_size",
"n_fft noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates a profile",
"a = ksi / (1 + ksi) vk = a",
"axis=0)) noise_mu2 = (noise_mean / n_frames) ** 2 return NoiseProfile(sampling_rate,",
":param sampling_rate: the sampling rate of the audio :param window_size:",
"profile. :param wav: a speech waveform as a numpy array",
"elif _input.dtype == np.int16: return _input / 32768., _input.dtype elif",
"% 2 == 1: window_size = window_size + 1 perc",
"portions of the Software. # # THE SOFTWARE IS PROVIDED",
"len1) win = np.hanning(window_size) win = win * len2 /",
"This code was extracted from the logmmse package (https://pypi.org/project/logmmse/) and",
"value will be picked if left as 0. :return: a",
"noise update. While the voice activation detection value is below",
"int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes",
"= 10 ** (-25 / 10) x_old = np.zeros(p.len1) xk_prev",
"to meet my needs. import numpy as np import math",
"sig * hw xk_prev = sig ** 2 xi_w =",
"dtype == np.float64: return _input, np.float64 elif dtype == np.float32:",
"== 0: ksi = aa + (1 - aa) *",
"* p.len2) aa = 0.98 mu = 0.98 ksi_min =",
"MIT License (MIT) # # Copyright (c) 2015 braindead #",
"# # The above copyright notice and this permission notice",
"xk_prev.all() == 0: ksi = aa + (1 - aa)",
"- 1, 0) else: ksi = aa * xk_prev /",
"== np.uint8: return ((_input * 128) + 128).astype(np.uint8) elif dtype",
"p.noise_mu2 for k in range(0, nframes * p.len2, p.len2): insign",
"1e-8)) hw = a * np.exp(ei_vk) sig = sig *",
"collections import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2",
"will be picked if left as 0. :return: a NoiseProfile",
"and associated documentation files (the \"Software\"), to deal # in",
"Software without restriction, including without limitation the rights # to",
"n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans the",
"and to permit persons to whom the Software is #",
"on. A default value will be picked if left as",
"np.sum(log_sigma_k) / p.window_size if vad_decision < eta: noise_mu2 = mu",
"len1, len2, win, n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15):",
"copies of the Software, and to permit persons to whom",
"/ np.sum(win) n_fft = 2 * window_size noise_mean = np.zeros(n_fft)",
"hereby granted, free of charge, to any person obtaining a",
"* np.maximum(gammak - 1, 0) else: ksi = aa *",
"this permission notice shall be included in all # copies",
"ksi = aa * xk_prev / noise_mu2 + (1 -",
"OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"distribute, sublicense, and/or sell # copies of the Software, and",
"ksi) vk = a * gammak ei_vk = 0.5 *",
"spec = np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec) sig2 =",
"OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"win * len2 / np.sum(win) n_fft = 2 * window_size",
"noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans the noise",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #",
"THE # SOFTWARE. # # # This code was extracted",
"the sampling rate of the audio :param window_size: the size",
"np.float64: return _input, _input.dtype elif _input.dtype == np.float32: return _input.astype(np.float64),",
"perc = 50 len1 = int(math.floor(window_size * perc / 100))",
"np.int32: return _input / 2147483648., _input.dtype raise ValueError('Unsupported wave file",
"def denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans the noise from",
"import expn from collections import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate",
"aa * xk_prev / noise_mu2 + (1 - aa) *",
"128., _input.dtype elif _input.dtype == np.int16: return _input / 32768.,",
"similar (or a segment of the same) waveform. :param eta:",
"np.int32: print(_input) return (_input * 2147483648).astype(np.int32) raise ValueError('Unsupported wave file",
"the window the logmmse algorithm operates on. A default value",
"the interface to meet my needs. import numpy as np",
"OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH",
"n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft,",
"one used to create the noise profile. :param wav: a",
"10 ** (-25 / 10) x_old = np.zeros(p.len1) xk_prev =",
"deal # in the Software without restriction, including without limitation",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #",
"def profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates a profile of the",
"math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes * p.len2) aa =",
"(_input * 32768).astype(np.int16) elif dtype == np.int32: print(_input) return (_input",
"the one used to create the noise profile. :param wav:",
"gammak = np.minimum(sig2 / noise_mu2, 40) if xk_prev.all() == 0:",
"be included in all # copies or substantial portions of",
"= sig ** 2 xi_w = np.fft.ifft(hw * spec, p.n_fft,",
"noise profile. :return: the clean wav as a numpy array",
"to 0 to disable updating the noise profile. :return: the",
"p.win * wav[k:k + p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0)",
"np.uint8: return (_input - 128) / 128., _input.dtype elif _input.dtype",
"the Software. # # THE SOFTWARE IS PROVIDED \"AS IS\",",
"= p.noise_mu2 for k in range(0, nframes * p.len2, p.len2):",
"a segment of the same) waveform. :param eta: voice threshold",
"continuously updated throughout the audio. Set to 0 to disable",
"copy, modify, merge, publish, distribute, sublicense, and/or sell # copies",
"# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"2 gammak = np.minimum(sig2 / noise_mu2, 40) if xk_prev.all() ==",
"raise ValueError('Unsupported wave file format') def from_float(_input, dtype): if dtype",
"floats or ints of the same length. \"\"\" wav, dtype",
"noise_profile nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2))",
"p.window_size if vad_decision < eta: noise_mu2 = mu * noise_mu2",
"return _input.astype(np.float64), _input.dtype elif _input.dtype == np.uint8: return (_input -",
"noise_mu2 = (noise_mean / n_frames) ** 2 return NoiseProfile(sampling_rate, window_size,",
"window_size % 2 == 1: window_size = window_size + 1",
"gammak ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) hw =",
"= aa + (1 - aa) * np.maximum(gammak - 1,",
"/ noise_mu2, 40) if xk_prev.all() == 0: ksi = aa",
"window_size: the size of the window the logmmse algorithm operates",
"software and associated documentation files (the \"Software\"), to deal #",
"of the window the logmmse algorithm operates on. A default",
"from a speech waveform given a noise profile. The waveform",
"int(math.floor(window_size * perc / 100)) len2 = int(window_size - len1)",
"x_final[k:k + p.len2] = x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size]",
"+ ksi) vad_decision = np.sum(log_sigma_k) / p.window_size if vad_decision <",
"xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output =",
"ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) hw = a",
"# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"= (noise_mean / n_frames) ** 2 return NoiseProfile(sampling_rate, window_size, len1,",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR",
"the Software without restriction, including without limitation the rights #",
"profile. :return: the clean wav as a numpy array of",
"# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"from the logmmse package (https://pypi.org/project/logmmse/) and I # simply modified",
"+ p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec)",
"left as 0. :return: a NoiseProfile object \"\"\" noise, dtype",
"elif dtype == np.int16: return (_input * 32768).astype(np.int16) elif dtype",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #",
"return _input / 2147483648., _input.dtype raise ValueError('Unsupported wave file format')",
"waveform containing noise ONLY, as a numpy array of floats",
"= a * gammak ei_vk = 0.5 * expn(1, np.maximum(vk,",
"ints. :param sampling_rate: the sampling rate of the audio :param",
"as np import math from scipy.special import expn from collections",
"create the noise profile. :param wav: a speech waveform as",
"return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2) def denoise(wav,",
"= np.absolute(spec) sig2 = sig ** 2 gammak = np.minimum(sig2",
"= xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output = np.pad(output, (0,",
"== np.int16: return _input / 32768., _input.dtype elif _input.dtype ==",
"from a similar (or a segment of the same) waveform.",
"SOFTWARE. # # # This code was extracted from the",
"window the logmmse algorithm operates on. A default value will",
"updating the noise profile. :return: the clean wav as a",
"p.len2, p.len2): insign = p.win * wav[k:k + p.window_size] spec",
"included in all # copies or substantial portions of the",
":param noise_profile: a NoiseProfile object that was created from a",
"# of this software and associated documentation files (the \"Software\"),",
"furnished to do so, subject to the following conditions: #",
"to do so, subject to the following conditions: # #",
"/ p.len2)) x_final = np.zeros(nframes * p.len2) aa = 0.98",
"# The above copyright notice and this permission notice shall",
"** 2 xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w",
"n_fft = 2 * window_size noise_mean = np.zeros(n_fft) n_frames =",
"SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"noise profile. The waveform must have the same sampling rate",
"np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k +",
"a copy # of this software and associated documentation files",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF",
"= win * len2 / np.sum(win) n_fft = 2 *",
"= int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2)) x_final =",
"logmmse algorithm operates on. A default value will be picked",
"+= np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0)) noise_mu2 =",
"ksi) vad_decision = np.sum(log_sigma_k) / p.window_size if vad_decision < eta:",
"- 1, 0) ksi = np.maximum(ksi_min, ksi) log_sigma_k = gammak",
"< eta: noise_mu2 = mu * noise_mu2 + (1 -",
"ksi / (1 + ksi) vk = a * gammak",
"* p.len2, p.len2): insign = p.win * wav[k:k + p.window_size]",
"range(0, nframes * p.len2, p.len2): insign = p.win * wav[k:k",
"permission notice shall be included in all # copies or",
"# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"or ints of the same length. \"\"\" wav, dtype =",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"(noise_mean / n_frames) ** 2 return NoiseProfile(sampling_rate, window_size, len1, len2,",
"np import math from scipy.special import expn from collections import",
"mu * noise_mu2 + (1 - mu) * sig2 a",
"from collections import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1",
"NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE",
"the audio :param window_size: the size of the window the",
"np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec) sig2 = sig **",
"noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates a profile of",
"clean wav as a numpy array of floats or ints",
"ints of the same length. \"\"\" wav, dtype = to_float(wav)",
"insign = p.win * wav[k:k + p.window_size] spec = np.fft.fft(insign,",
"= ksi / (1 + ksi) vk = a *",
"win = np.hanning(window_size) win = win * len2 / np.sum(win)",
"== np.float32: return _input.astype(np.float32) elif dtype == np.uint8: return ((_input",
"following conditions: # # The above copyright notice and this",
"noise, dtype = to_float(noise) noise += np.finfo(np.float64).eps if window_size ==",
"p.len2] = x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output =",
"to deal # in the Software without restriction, including without",
"_input / 32768., _input.dtype elif _input.dtype == np.int32: return _input",
"2147483648., _input.dtype raise ValueError('Unsupported wave file format') def from_float(_input, dtype):",
"(_input - 128) / 128., _input.dtype elif _input.dtype == np.int16:",
"def from_float(_input, dtype): if dtype == np.float64: return _input, np.float64",
"* n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size],",
"a similar (or a segment of the same) waveform. :param",
"0. :return: a NoiseProfile object \"\"\" noise, dtype = to_float(noise)",
"conditions: # # The above copyright notice and this permission",
"the noise profile. :param wav: a speech waveform as a",
"noise_mu2 = p.noise_mu2 for k in range(0, nframes * p.len2,",
"ksi) - np.log(1 + ksi) vad_decision = np.sum(log_sigma_k) / p.window_size",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #",
"to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS",
"** 2 return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2)",
"a waveform containing noise ONLY, as a numpy array of",
"nframes * p.len2, p.len2): insign = p.win * wav[k:k +",
"the logmmse package (https://pypi.org/project/logmmse/) and I # simply modified the",
"** 2 gammak = np.minimum(sig2 / noise_mu2, 40) if xk_prev.all()",
"throughout the audio. Set to 0 to disable updating the",
"noise_mean = np.zeros(n_fft) n_frames = len(noise) // window_size for j",
"/ 100)) len2 = int(window_size - len1) win = np.hanning(window_size)",
"FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN",
"output def to_float(_input): if _input.dtype == np.float64: return _input, _input.dtype",
"noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0)) noise_mu2",
"sig2 = sig ** 2 gammak = np.minimum(sig2 / noise_mu2,",
"np.float32: return _input.astype(np.float32) elif dtype == np.uint8: return ((_input *",
"+ (1 - mu) * sig2 a = ksi /",
"= noise_profile nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size /",
"len2 win n_fft noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates",
"a * np.exp(ei_vk) sig = sig * hw xk_prev =",
"rate of the audio :param window_size: the size of the",
"int(math.floor(0.02 * sampling_rate)) if window_size % 2 == 1: window_size",
"= window_size + 1 perc = 50 len1 = int(math.floor(window_size",
"return _input, _input.dtype elif _input.dtype == np.float32: return _input.astype(np.float64), _input.dtype",
"return output def to_float(_input): if _input.dtype == np.float64: return _input,",
"ksi/(1 + ksi) - np.log(1 + ksi) vad_decision = np.sum(log_sigma_k)",
"return (_input - 128) / 128., _input.dtype elif _input.dtype ==",
"import math from scipy.special import expn from collections import namedtuple",
"of the same) waveform. :param eta: voice threshold for noise",
"/ p.window_size if vad_decision < eta: noise_mu2 = mu *",
"and/or sell # copies of the Software, and to permit",
"the rights # to use, copy, modify, merge, publish, distribute,",
"given a noise profile. The waveform must have the same",
"all # copies or substantial portions of the Software. #",
"ksi = aa + (1 - aa) * np.maximum(gammak -",
"Set to 0 to disable updating the noise profile. :return:",
"spec, p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k + p.len2] =",
"= 50 len1 = int(math.floor(window_size * perc / 100)) len2",
"hw = a * np.exp(ei_vk) sig = sig * hw",
":param eta: voice threshold for noise update. While the voice",
"aa) * np.maximum(gammak - 1, 0) else: ksi = aa",
"below this threshold, the noise profile will be continuously updated",
"sig2 a = ksi / (1 + ksi) vk =",
"0.98 ksi_min = 10 ** (-25 / 10) x_old =",
"notice and this permission notice shall be included in all",
"<reponame>dbonattoj/Real-Time-Voice-Cloning # The MIT License (MIT) # # Copyright (c)",
"a noise profile. The waveform must have the same sampling",
"dtype == np.int32: print(_input) return (_input * 2147483648).astype(np.int32) raise ValueError('Unsupported",
"Copyright (c) 2015 braindead # # Permission is hereby granted,",
"is hereby granted, free of charge, to any person obtaining",
"a numpy array of floats or ints. :param sampling_rate: the",
"* noise[j:j + window_size], n_fft, axis=0)) noise_mu2 = (noise_mean /",
"modified the interface to meet my needs. import numpy as",
"as a numpy array of floats or ints. :param sampling_rate:",
"= int(math.floor(0.02 * sampling_rate)) if window_size % 2 == 1:",
"= np.zeros(nframes * p.len2) aa = 0.98 mu = 0.98",
"of the noise in a given waveform. :param noise: a",
"noise_mu2 + (1 - aa) * np.maximum(gammak - 1, 0)",
"algorithm operates on. A default value will be picked if",
"window_size == 0: window_size = int(math.floor(0.02 * sampling_rate)) if window_size",
"_input.astype(np.float64), _input.dtype elif _input.dtype == np.uint8: return (_input - 128)",
"a speech waveform as a numpy array of floats or",
"np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k in",
"+ ksi) vk = a * gammak ei_vk = 0.5",
"profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates a profile of the noise",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR",
"a profile of the noise in a given waveform. :param",
"- mu) * sig2 a = ksi / (1 +",
"np.exp(ei_vk) sig = sig * hw xk_prev = sig **",
"person obtaining a copy # of this software and associated",
"# # Permission is hereby granted, free of charge, to",
"without restriction, including without limitation the rights # to use,",
"sampling_rate, window_size=0): \"\"\" Creates a profile of the noise in",
"_input, _input.dtype elif _input.dtype == np.float32: return _input.astype(np.float64), _input.dtype elif",
"p.len2) - math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes * p.len2)",
"= from_float(x_final, dtype) output = np.pad(output, (0, len(wav) - len(output)),",
"subject to the following conditions: # # The above copyright",
"/ n_frames) ** 2 return NoiseProfile(sampling_rate, window_size, len1, len2, win,",
"The waveform must have the same sampling rate as the",
"dtype == np.float32: return _input.astype(np.float32) elif dtype == np.uint8: return",
"the noise profile. :return: the clean wav as a numpy",
"- aa) * np.maximum(gammak - 1, 0) ksi = np.maximum(ksi_min,",
"= np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k",
"a numpy array of floats or ints of the same",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"_input.dtype == np.int16: return _input / 32768., _input.dtype elif _input.dtype",
"= gammak * ksi/(1 + ksi) - np.log(1 + ksi)",
"import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2 win",
"used to create the noise profile. :param wav: a speech",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"2 == 1: window_size = window_size + 1 perc =",
"noise_profile: a NoiseProfile object that was created from a similar",
"ksi_min = 10 ** (-25 / 10) x_old = np.zeros(p.len1)",
"given waveform. :param noise: a waveform containing noise ONLY, as",
"profile will be continuously updated throughout the audio. Set to",
"that was created from a similar (or a segment of",
"np.finfo(np.float64).eps if window_size == 0: window_size = int(math.floor(0.02 * sampling_rate))",
"update. While the voice activation detection value is below this",
"for k in range(0, nframes * p.len2, p.len2): insign =",
"length. \"\"\" wav, dtype = to_float(wav) wav += np.finfo(np.float64).eps p",
"= np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec) sig2 = sig",
"or substantial portions of the Software. # # THE SOFTWARE",
"== np.int32: print(_input) return (_input * 2147483648).astype(np.int32) raise ValueError('Unsupported wave",
"_input.dtype == np.uint8: return (_input - 128) / 128., _input.dtype",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS",
"the audio. Set to 0 to disable updating the noise",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"as a numpy array of floats or ints of the",
"k in range(0, nframes * p.len2, p.len2): insign = p.win",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"win = win * len2 / np.sum(win) n_fft = 2",
"= np.pad(output, (0, len(wav) - len(output)), mode=\"constant\") return output def",
"10) x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2",
"+= np.finfo(np.float64).eps if window_size == 0: window_size = int(math.floor(0.02 *",
"* 128) + 128).astype(np.uint8) elif dtype == np.int16: return (_input",
"USE OR OTHER DEALINGS IN THE # SOFTWARE. # #",
"numpy as np import math from scipy.special import expn from",
"window_size = window_size + 1 perc = 50 len1 =",
"0 to disable updating the noise profile. :return: the clean",
"have the same sampling rate as the one used to",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"needs. import numpy as np import math from scipy.special import",
"CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION",
"if window_size == 0: window_size = int(math.floor(0.02 * sampling_rate)) if",
"# Permission is hereby granted, free of charge, to any",
"of charge, to any person obtaining a copy # of",
"the noise profile will be continuously updated throughout the audio.",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #",
"merge, publish, distribute, sublicense, and/or sell # copies of the",
"1: window_size = window_size + 1 perc = 50 len1",
"* spec, p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k + p.len2]",
"_input.dtype == np.float32: return _input.astype(np.float64), _input.dtype elif _input.dtype == np.uint8:",
"32768., _input.dtype elif _input.dtype == np.int32: return _input / 2147483648.,",
"# # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"/ p.len2) - math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes *",
"from_float(x_final, dtype) output = np.pad(output, (0, len(wav) - len(output)), mode=\"constant\")",
"the clean wav as a numpy array of floats or",
"= p.win * wav[k:k + p.window_size] spec = np.fft.fft(insign, p.n_fft,",
"NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT",
"The MIT License (MIT) # # Copyright (c) 2015 braindead",
"== np.float64: return _input, np.float64 elif dtype == np.float32: return",
"voice activation detection value is below this threshold, the noise",
"* hw xk_prev = sig ** 2 xi_w = np.fft.ifft(hw",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR",
"range(0, window_size * n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j",
"dtype == np.int16: return (_input * 32768).astype(np.int16) elif dtype ==",
":param window_size: the size of the window the logmmse algorithm",
"be picked if left as 0. :return: a NoiseProfile object",
"NoiseProfile, eta=0.15): \"\"\" Cleans the noise from a speech waveform",
"* 32768).astype(np.int16) elif dtype == np.int32: print(_input) return (_input *",
"of floats or ints. :param sampling_rate: the sampling rate of",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER",
"p = noise_profile nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size",
"x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output = from_float(x_final, dtype)",
"so, subject to the following conditions: # # The above",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #",
"= np.real(xi_w) x_final[k:k + p.len2] = x_old + xi_w[0:p.len1] x_old",
"a speech waveform given a noise profile. The waveform must",
"win, n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans",
"(-25 / 10) x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2",
"# This code was extracted from the logmmse package (https://pypi.org/project/logmmse/)",
"DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF",
"output = from_float(x_final, dtype) output = np.pad(output, (0, len(wav) -",
"if window_size % 2 == 1: window_size = window_size +",
"# # Copyright (c) 2015 braindead # # Permission is",
"scipy.special import expn from collections import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\",",
"- len1) win = np.hanning(window_size) win = win * len2",
"eta: voice threshold for noise update. While the voice activation",
"= sig ** 2 gammak = np.minimum(sig2 / noise_mu2, 40)",
"dtype): if dtype == np.float64: return _input, np.float64 elif dtype",
"- np.log(1 + ksi) vad_decision = np.sum(log_sigma_k) / p.window_size if",
"np.uint8: return ((_input * 128) + 128).astype(np.uint8) elif dtype ==",
"value is below this threshold, the noise profile will be",
"(0, len(wav) - len(output)), mode=\"constant\") return output def to_float(_input): if",
"to_float(noise) noise += np.finfo(np.float64).eps if window_size == 0: window_size =",
"len2 = int(window_size - len1) win = np.hanning(window_size) win =",
"was created from a similar (or a segment of the",
"the following conditions: # # The above copyright notice and",
"FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"len2, win, n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\"",
"== np.uint8: return (_input - 128) / 128., _input.dtype elif",
"== np.int16: return (_input * 32768).astype(np.int16) elif dtype == np.int32:",
"* noise_mu2 + (1 - mu) * sig2 a =",
"* xk_prev / noise_mu2 + (1 - aa) * np.maximum(gammak",
"2 xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w =",
"sampling_rate)) if window_size % 2 == 1: window_size = window_size",
"np.absolute(spec) sig2 = sig ** 2 gammak = np.minimum(sig2 /",
"dtype) output = np.pad(output, (0, len(wav) - len(output)), mode=\"constant\") return",
":param noise: a waveform containing noise ONLY, as a numpy",
"THE USE OR OTHER DEALINGS IN THE # SOFTWARE. #",
"p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0) sig = np.absolute(spec) sig2",
"n_frames) ** 2 return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft,",
"NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2 win n_fft noise_mu2\")",
"speech waveform given a noise profile. The waveform must have",
"np.minimum(sig2 / noise_mu2, 40) if xk_prev.all() == 0: ksi =",
"== np.int32: return _input / 2147483648., _input.dtype raise ValueError('Unsupported wave",
"same) waveform. :param eta: voice threshold for noise update. While",
"the Software, and to permit persons to whom the Software",
"DEALINGS IN THE # SOFTWARE. # # # This code",
"ksi = np.maximum(ksi_min, ksi) log_sigma_k = gammak * ksi/(1 +",
"100)) len2 = int(window_size - len1) win = np.hanning(window_size) win",
"+= np.finfo(np.float64).eps p = noise_profile nframes = int(math.floor(len(wav) / p.len2)",
"// window_size for j in range(0, window_size * n_frames, window_size):",
"_input.dtype elif _input.dtype == np.uint8: return (_input - 128) /",
"noise ONLY, as a numpy array of floats or ints.",
"default value will be picked if left as 0. :return:",
"floats or ints. :param noise_profile: a NoiseProfile object that was",
"ksi) log_sigma_k = gammak * ksi/(1 + ksi) - np.log(1",
"picked if left as 0. :return: a NoiseProfile object \"\"\"",
"32768).astype(np.int16) elif dtype == np.int32: print(_input) return (_input * 2147483648).astype(np.int32)",
"np.maximum(gammak - 1, 0) else: ksi = aa * xk_prev",
"FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"a NoiseProfile object \"\"\" noise, dtype = to_float(noise) noise +=",
"persons to whom the Software is # furnished to do",
"a NoiseProfile object that was created from a similar (or",
"vk = a * gammak ei_vk = 0.5 * expn(1,",
"# SOFTWARE. # # # This code was extracted from",
"ValueError('Unsupported wave file format') def from_float(_input, dtype): if dtype ==",
"sampling_rate: the sampling rate of the audio :param window_size: the",
"of the audio :param window_size: the size of the window",
"/ 128., _input.dtype elif _input.dtype == np.int16: return _input /",
"Creates a profile of the noise in a given waveform.",
"associated documentation files (the \"Software\"), to deal # in the",
"same length. \"\"\" wav, dtype = to_float(wav) wav += np.finfo(np.float64).eps",
"MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"= int(window_size - len1) win = np.hanning(window_size) win = win",
"the noise from a speech waveform given a noise profile.",
"Software. # # THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"to any person obtaining a copy # of this software",
":param wav: a speech waveform as a numpy array of",
"profile. The waveform must have the same sampling rate as",
"a numpy array of floats or ints. :param noise_profile: a",
"updated throughout the audio. Set to 0 to disable updating",
"Cleans the noise from a speech waveform given a noise",
"in all # copies or substantial portions of the Software.",
"this software and associated documentation files (the \"Software\"), to deal",
"of the Software, and to permit persons to whom the",
"for noise update. While the voice activation detection value is",
"ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN",
"array of floats or ints. :param noise_profile: a NoiseProfile object",
"of the same length. \"\"\" wav, dtype = to_float(wav) wav",
"if xk_prev.all() == 0: ksi = aa + (1 -",
"vad_decision < eta: noise_mu2 = mu * noise_mu2 + (1",
"np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0)) noise_mu2 = (noise_mean",
"# Copyright (c) 2015 braindead # # Permission is hereby",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY,",
"n_fft, axis=0)) noise_mu2 = (noise_mean / n_frames) ** 2 return",
"noise in a given waveform. :param noise: a waveform containing",
"from scipy.special import expn from collections import namedtuple NoiseProfile =",
"elif _input.dtype == np.float32: return _input.astype(np.float64), _input.dtype elif _input.dtype ==",
"shall be included in all # copies or substantial portions",
"np.int16: return (_input * 32768).astype(np.int16) elif dtype == np.int32: print(_input)",
"Software is # furnished to do so, subject to the",
"waveform must have the same sampling rate as the one",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"elif _input.dtype == np.uint8: return (_input - 128) / 128.,",
"whom the Software is # furnished to do so, subject",
"sublicense, and/or sell # copies of the Software, and to",
"xk_prev = sig ** 2 xi_w = np.fft.ifft(hw * spec,",
"THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"(or a segment of the same) waveform. :param eta: voice",
"substantial portions of the Software. # # THE SOFTWARE IS",
"notice shall be included in all # copies or substantial",
"window_size=0): \"\"\" Creates a profile of the noise in a",
"do so, subject to the following conditions: # # The",
"LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING",
"namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2 win n_fft noise_mu2\") def profile_noise(noise,",
"\"sampling_rate window_size len1 len2 win n_fft noise_mu2\") def profile_noise(noise, sampling_rate,",
"profile of the noise in a given waveform. :param noise:",
"as the one used to create the noise profile. :param",
"in the Software without restriction, including without limitation the rights",
"window_size for j in range(0, window_size * n_frames, window_size): noise_mean",
"wav, dtype = to_float(wav) wav += np.finfo(np.float64).eps p = noise_profile",
"noise_mu2 = mu * noise_mu2 + (1 - mu) *",
"_input, np.float64 elif dtype == np.float32: return _input.astype(np.float32) elif dtype",
"xi_w = np.real(xi_w) x_final[k:k + p.len2] = x_old + xi_w[0:p.len1]",
"* wav[k:k + p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0) sig",
"+ (1 - aa) * np.maximum(gammak - 1, 0) else:",
"# furnished to do so, subject to the following conditions:",
"namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2 win n_fft",
"the noise in a given waveform. :param noise: a waveform",
"any person obtaining a copy # of this software and",
"ARISING FROM, # OUT OF OR IN CONNECTION WITH THE",
"waveform as a numpy array of floats or ints. :param",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"* np.exp(ei_vk) sig = sig * hw xk_prev = sig",
"- len(output)), mode=\"constant\") return output def to_float(_input): if _input.dtype ==",
"if _input.dtype == np.float64: return _input, _input.dtype elif _input.dtype ==",
"KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO",
"np.float64 elif dtype == np.float32: return _input.astype(np.float32) elif dtype ==",
"OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"(1 - aa) * np.maximum(gammak - 1, 0) ksi =",
"restriction, including without limitation the rights # to use, copy,",
"rate as the one used to create the noise profile.",
"p.n_fft, axis=0) sig = np.absolute(spec) sig2 = sig ** 2",
"dtype = to_float(wav) wav += np.finfo(np.float64).eps p = noise_profile nframes",
"code was extracted from the logmmse package (https://pypi.org/project/logmmse/) and I",
"mu = 0.98 ksi_min = 10 ** (-25 / 10)",
"mu) * sig2 a = ksi / (1 + ksi)",
"as 0. :return: a NoiseProfile object \"\"\" noise, dtype =",
"2015 braindead # # Permission is hereby granted, free of",
"output = np.pad(output, (0, len(wav) - len(output)), mode=\"constant\") return output",
"elif _input.dtype == np.int32: return _input / 2147483648., _input.dtype raise",
"threshold for noise update. While the voice activation detection value",
"including without limitation the rights # to use, copy, modify,",
"0: window_size = int(math.floor(0.02 * sampling_rate)) if window_size % 2",
"copyright notice and this permission notice shall be included in",
"= to_float(noise) noise += np.finfo(np.float64).eps if window_size == 0: window_size",
"sampling rate of the audio :param window_size: the size of",
"# simply modified the interface to meet my needs. import",
"len2 / np.sum(win) n_fft = 2 * window_size noise_mean =",
"I # simply modified the interface to meet my needs.",
"NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2) def denoise(wav, noise_profile:",
"1, 0) else: ksi = aa * xk_prev / noise_mu2",
"activation detection value is below this threshold, the noise profile",
"ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED",
"free of charge, to any person obtaining a copy #",
"files (the \"Software\"), to deal # in the Software without",
"+ xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output",
"\"\"\" noise, dtype = to_float(noise) noise += np.finfo(np.float64).eps if window_size",
"np.float64: return _input, np.float64 elif dtype == np.float32: return _input.astype(np.float32)",
"of floats or ints. :param noise_profile: a NoiseProfile object that",
"aa = 0.98 mu = 0.98 ksi_min = 10 **",
"_input.dtype == np.float64: return _input, _input.dtype elif _input.dtype == np.float32:",
"\"\"\" wav, dtype = to_float(wav) wav += np.finfo(np.float64).eps p =",
"window_size noise_mean = np.zeros(n_fft) n_frames = len(noise) // window_size for",
"= int(math.floor(window_size * perc / 100)) len2 = int(window_size -",
"IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"np.pad(output, (0, len(wav) - len(output)), mode=\"constant\") return output def to_float(_input):",
"0) else: ksi = aa * xk_prev / noise_mu2 +",
"elif dtype == np.int32: print(_input) return (_input * 2147483648).astype(np.int32) raise",
"speech waveform as a numpy array of floats or ints.",
"== np.float64: return _input, _input.dtype elif _input.dtype == np.float32: return",
"128) + 128).astype(np.uint8) elif dtype == np.int16: return (_input *",
"of the Software. # # THE SOFTWARE IS PROVIDED \"AS",
"= len(noise) // window_size for j in range(0, window_size *",
"meet my needs. import numpy as np import math from",
"math from scipy.special import expn from collections import namedtuple NoiseProfile",
"to disable updating the noise profile. :return: the clean wav",
"np.finfo(np.float64).eps p = noise_profile nframes = int(math.floor(len(wav) / p.len2) -",
"nframes = int(math.floor(len(wav) / p.len2) - math.floor(p.window_size / p.len2)) x_final",
"0: ksi = aa + (1 - aa) * np.maximum(gammak",
"the voice activation detection value is below this threshold, the",
"disable updating the noise profile. :return: the clean wav as",
":return: the clean wav as a numpy array of floats",
"eta=0.15): \"\"\" Cleans the noise from a speech waveform given",
"noise from a speech waveform given a noise profile. The",
"np.real(xi_w) x_final[k:k + p.len2] = x_old + xi_w[0:p.len1] x_old =",
"braindead # # Permission is hereby granted, free of charge,",
"p.len2)) x_final = np.zeros(nframes * p.len2) aa = 0.98 mu",
"window_size): noise_mean += np.absolute(np.fft.fft(win * noise[j:j + window_size], n_fft, axis=0))",
"+ window_size], n_fft, axis=0)) noise_mu2 = (noise_mean / n_frames) **",
"* np.maximum(gammak - 1, 0) ksi = np.maximum(ksi_min, ksi) log_sigma_k",
"print(_input) return (_input * 2147483648).astype(np.int32) raise ValueError('Unsupported wave file format')",
"interface to meet my needs. import numpy as np import",
"simply modified the interface to meet my needs. import numpy",
"denoise(wav, noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans the noise from a",
"/ (1 + ksi) vk = a * gammak ei_vk",
"as a numpy array of floats or ints. :param noise_profile:",
"noise profile will be continuously updated throughout the audio. Set",
"+ 128).astype(np.uint8) elif dtype == np.int16: return (_input * 32768).astype(np.int16)",
"of this software and associated documentation files (the \"Software\"), to",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"operates on. A default value will be picked if left",
"2 * window_size noise_mean = np.zeros(n_fft) n_frames = len(noise) //",
"128).astype(np.uint8) elif dtype == np.int16: return (_input * 32768).astype(np.int16) elif",
"EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"audio :param window_size: the size of the window the logmmse",
"= 0.5 * expn(1, np.maximum(vk, 1e-8)) hw = a *",
"noise += np.finfo(np.float64).eps if window_size == 0: window_size = int(math.floor(0.02",
"50 len1 = int(math.floor(window_size * perc / 100)) len2 =",
"be continuously updated throughout the audio. Set to 0 to",
"the size of the window the logmmse algorithm operates on.",
"to create the noise profile. :param wav: a speech waveform",
"# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS",
"= aa * xk_prev / noise_mu2 + (1 - aa)",
"* sig2 a = ksi / (1 + ksi) vk",
"0.5 * expn(1, np.maximum(vk, 1e-8)) hw = a * np.exp(ei_vk)",
"window_size, len1, len2, win, n_fft, noise_mu2) def denoise(wav, noise_profile: NoiseProfile,",
"+ p.len2] = x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output",
"** (-25 / 10) x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1)",
"from_float(_input, dtype): if dtype == np.float64: return _input, np.float64 elif",
"np.maximum(gammak - 1, 0) ksi = np.maximum(ksi_min, ksi) log_sigma_k =",
"(the \"Software\"), to deal # in the Software without restriction,",
"return _input.astype(np.float32) elif dtype == np.uint8: return ((_input * 128)",
"return _input, np.float64 elif dtype == np.float32: return _input.astype(np.float32) elif",
"WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND",
"charge, to any person obtaining a copy # of this",
"permit persons to whom the Software is # furnished to",
"extracted from the logmmse package (https://pypi.org/project/logmmse/) and I # simply",
"array of floats or ints. :param sampling_rate: the sampling rate",
"THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE",
"np.maximum(ksi_min, ksi) log_sigma_k = gammak * ksi/(1 + ksi) -",
"object that was created from a similar (or a segment",
"the Software is # furnished to do so, subject to",
"(1 - aa) * np.maximum(gammak - 1, 0) else: ksi",
"While the voice activation detection value is below this threshold,",
"above copyright notice and this permission notice shall be included",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED,",
"2 return NoiseProfile(sampling_rate, window_size, len1, len2, win, n_fft, noise_mu2) def",
"expn from collections import namedtuple NoiseProfile = namedtuple(\"NoiseProfile\", \"sampling_rate window_size",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"limitation the rights # to use, copy, modify, merge, publish,",
"/ 10) x_old = np.zeros(p.len1) xk_prev = np.zeros(p.len1) noise_mu2 =",
"the same sampling rate as the one used to create",
"threshold, the noise profile will be continuously updated throughout the",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #",
"xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output = np.pad(output, (0, len(wav)",
"without limitation the rights # to use, copy, modify, merge,",
"== 0: window_size = int(math.floor(0.02 * sampling_rate)) if window_size %",
"or ints. :param noise_profile: a NoiseProfile object that was created",
"return (_input * 32768).astype(np.int16) elif dtype == np.int32: print(_input) return",
"\"\"\" Cleans the noise from a speech waveform given a",
"_input.dtype elif _input.dtype == np.float32: return _input.astype(np.float64), _input.dtype elif _input.dtype",
"j in range(0, window_size * n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win",
"noise: a waveform containing noise ONLY, as a numpy array",
"# copies or substantial portions of the Software. # #",
"EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"# The MIT License (MIT) # # Copyright (c) 2015",
"# in the Software without restriction, including without limitation the",
"x_old = xi_w[p.len1:p.window_size] output = from_float(x_final, dtype) output = np.pad(output,",
"documentation files (the \"Software\"), to deal # in the Software",
"dtype = to_float(noise) noise += np.finfo(np.float64).eps if window_size == 0:",
"/ 2147483648., _input.dtype raise ValueError('Unsupported wave file format') def from_float(_input,",
"* gammak ei_vk = 0.5 * expn(1, np.maximum(vk, 1e-8)) hw",
"copies or substantial portions of the Software. # # THE",
"logmmse package (https://pypi.org/project/logmmse/) and I # simply modified the interface",
"return ((_input * 128) + 128).astype(np.uint8) elif dtype == np.int16:",
"len(output)), mode=\"constant\") return output def to_float(_input): if _input.dtype == np.float64:",
"and I # simply modified the interface to meet my",
"is below this threshold, the noise profile will be continuously",
"1 perc = 50 len1 = int(math.floor(window_size * perc /",
"window_size = int(math.floor(0.02 * sampling_rate)) if window_size % 2 ==",
"(MIT) # # Copyright (c) 2015 braindead # # Permission",
"must have the same sampling rate as the one used",
"a given waveform. :param noise: a waveform containing noise ONLY,",
"waveform. :param eta: voice threshold for noise update. While the",
"same sampling rate as the one used to create the",
"= 0.98 ksi_min = 10 ** (-25 / 10) x_old",
"np.int16: return _input / 32768., _input.dtype elif _input.dtype == np.int32:",
"numpy array of floats or ints of the same length.",
"size of the window the logmmse algorithm operates on. A",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT",
"waveform. :param noise: a waveform containing noise ONLY, as a",
"sell # copies of the Software, and to permit persons",
"elif dtype == np.uint8: return ((_input * 128) + 128).astype(np.uint8)",
"len1 len2 win n_fft noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0): \"\"\"",
"OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT",
"sig = np.absolute(spec) sig2 = sig ** 2 gammak =",
"this threshold, the noise profile will be continuously updated throughout",
"_input.dtype elif _input.dtype == np.int32: return _input / 2147483648., _input.dtype",
"def to_float(_input): if _input.dtype == np.float64: return _input, _input.dtype elif",
"+ (1 - aa) * np.maximum(gammak - 1, 0) ksi",
"= 0.98 mu = 0.98 ksi_min = 10 ** (-25",
"noise_mu2 + (1 - mu) * sig2 a = ksi",
"OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"object \"\"\" noise, dtype = to_float(noise) noise += np.finfo(np.float64).eps if",
"eta: noise_mu2 = mu * noise_mu2 + (1 - mu)",
"publish, distribute, sublicense, and/or sell # copies of the Software,",
"- 128) / 128., _input.dtype elif _input.dtype == np.int16: return",
"audio. Set to 0 to disable updating the noise profile.",
"to the following conditions: # # The above copyright notice",
"format') def from_float(_input, dtype): if dtype == np.float64: return _input,",
"sig = sig * hw xk_prev = sig ** 2",
"if left as 0. :return: a NoiseProfile object \"\"\" noise,",
"and this permission notice shall be included in all #",
"vad_decision = np.sum(log_sigma_k) / p.window_size if vad_decision < eta: noise_mu2",
"wave file format') def from_float(_input, dtype): if dtype == np.float64:",
"/ 32768., _input.dtype elif _input.dtype == np.int32: return _input /",
"= x_old + xi_w[0:p.len1] x_old = xi_w[p.len1:p.window_size] output = from_float(x_final,",
"modify, merge, publish, distribute, sublicense, and/or sell # copies of",
"in a given waveform. :param noise: a waveform containing noise",
"* perc / 100)) len2 = int(window_size - len1) win",
"the same) waveform. :param eta: voice threshold for noise update.",
"OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION",
"the same length. \"\"\" wav, dtype = to_float(wav) wav +=",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"package (https://pypi.org/project/logmmse/) and I # simply modified the interface to",
"aa) * np.maximum(gammak - 1, 0) ksi = np.maximum(ksi_min, ksi)",
"Software, and to permit persons to whom the Software is",
"n_frames = len(noise) // window_size for j in range(0, window_size",
"= np.sum(log_sigma_k) / p.window_size if vad_decision < eta: noise_mu2 =",
"if vad_decision < eta: noise_mu2 = mu * noise_mu2 +",
"wav: a speech waveform as a numpy array of floats",
"= np.hanning(window_size) win = win * len2 / np.sum(win) n_fft",
"# to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"NoiseProfile object \"\"\" noise, dtype = to_float(noise) noise += np.finfo(np.float64).eps",
"the logmmse algorithm operates on. A default value will be",
"in range(0, window_size * n_frames, window_size): noise_mean += np.absolute(np.fft.fft(win *",
"else: ksi = aa * xk_prev / noise_mu2 + (1",
"OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
":return: a NoiseProfile object \"\"\" noise, dtype = to_float(noise) noise",
"np.hanning(window_size) win = win * len2 / np.sum(win) n_fft =",
"= namedtuple(\"NoiseProfile\", \"sampling_rate window_size len1 len2 win n_fft noise_mu2\") def",
"file format') def from_float(_input, dtype): if dtype == np.float64: return",
"window_size len1 len2 win n_fft noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0):",
"will be continuously updated throughout the audio. Set to 0",
"np.zeros(nframes * p.len2) aa = 0.98 mu = 0.98 ksi_min",
"window_size + 1 perc = 50 len1 = int(math.floor(window_size *",
"p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k + p.len2] = x_old",
"/ noise_mu2 + (1 - aa) * np.maximum(gammak - 1,",
"p.len2) aa = 0.98 mu = 0.98 ksi_min = 10",
"- math.floor(p.window_size / p.len2)) x_final = np.zeros(nframes * p.len2) aa",
"\"Software\"), to deal # in the Software without restriction, including",
"np.sum(win) n_fft = 2 * window_size noise_mean = np.zeros(n_fft) n_frames",
"== 1: window_size = window_size + 1 perc = 50",
"array of floats or ints of the same length. \"\"\"",
"dtype == np.uint8: return ((_input * 128) + 128).astype(np.uint8) elif",
"hw xk_prev = sig ** 2 xi_w = np.fft.ifft(hw *",
"sig ** 2 xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0)",
"= 2 * window_size noise_mean = np.zeros(n_fft) n_frames = len(noise)",
"np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k in range(0, nframes *",
"# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"import numpy as np import math from scipy.special import expn",
"40) if xk_prev.all() == 0: ksi = aa + (1",
"floats or ints. :param sampling_rate: the sampling rate of the",
"= np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w = np.real(xi_w) x_final[k:k",
"created from a similar (or a segment of the same)",
"np.float32: return _input.astype(np.float64), _input.dtype elif _input.dtype == np.uint8: return (_input",
"\"\"\" Creates a profile of the noise in a given",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"in range(0, nframes * p.len2, p.len2): insign = p.win *",
"* expn(1, np.maximum(vk, 1e-8)) hw = a * np.exp(ei_vk) sig",
"len1 = int(math.floor(window_size * perc / 100)) len2 = int(window_size",
"np.maximum(vk, 1e-8)) hw = a * np.exp(ei_vk) sig = sig",
"= sig * hw xk_prev = sig ** 2 xi_w",
"detection value is below this threshold, the noise profile will",
"IN THE # SOFTWARE. # # # This code was",
"wav += np.finfo(np.float64).eps p = noise_profile nframes = int(math.floor(len(wav) /",
"win n_fft noise_mu2\") def profile_noise(noise, sampling_rate, window_size=0): \"\"\" Creates a",
"_input.dtype elif _input.dtype == np.int16: return _input / 32768., _input.dtype",
"(https://pypi.org/project/logmmse/) and I # simply modified the interface to meet",
"+ 1 perc = 50 len1 = int(math.floor(window_size * perc",
"# copies of the Software, and to permit persons to",
"= a * np.exp(ei_vk) sig = sig * hw xk_prev",
"0) ksi = np.maximum(ksi_min, ksi) log_sigma_k = gammak * ksi/(1",
"granted, free of charge, to any person obtaining a copy",
"= to_float(wav) wav += np.finfo(np.float64).eps p = noise_profile nframes =",
"segment of the same) waveform. :param eta: voice threshold for",
"waveform given a noise profile. The waveform must have the",
"0.98 mu = 0.98 ksi_min = 10 ** (-25 /",
"to_float(wav) wav += np.finfo(np.float64).eps p = noise_profile nframes = int(math.floor(len(wav)",
"axis=0) sig = np.absolute(spec) sig2 = sig ** 2 gammak",
"= np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k in range(0, nframes",
"xk_prev = np.zeros(p.len1) noise_mu2 = p.noise_mu2 for k in range(0,",
"obtaining a copy # of this software and associated documentation",
"A default value will be picked if left as 0.",
"- aa) * np.maximum(gammak - 1, 0) else: ksi =",
"* sampling_rate)) if window_size % 2 == 1: window_size =",
"TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN",
"= mu * noise_mu2 + (1 - mu) * sig2",
"is # furnished to do so, subject to the following",
"= np.maximum(ksi_min, ksi) log_sigma_k = gammak * ksi/(1 + ksi)",
"to whom the Software is # furnished to do so,",
"containing noise ONLY, as a numpy array of floats or",
"to_float(_input): if _input.dtype == np.float64: return _input, _input.dtype elif _input.dtype",
"copy # of this software and associated documentation files (the",
"was extracted from the logmmse package (https://pypi.org/project/logmmse/) and I #",
"noise_profile: NoiseProfile, eta=0.15): \"\"\" Cleans the noise from a speech",
"THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE.",
"Permission is hereby granted, free of charge, to any person",
"_input.dtype raise ValueError('Unsupported wave file format') def from_float(_input, dtype): if",
"_input.astype(np.float32) elif dtype == np.uint8: return ((_input * 128) +",
"wav[k:k + p.window_size] spec = np.fft.fft(insign, p.n_fft, axis=0) sig =",
"log_sigma_k = gammak * ksi/(1 + ksi) - np.log(1 +",
"noise[j:j + window_size], n_fft, axis=0)) noise_mu2 = (noise_mean / n_frames)",
"elif dtype == np.float32: return _input.astype(np.float32) elif dtype == np.uint8:",
"License (MIT) # # Copyright (c) 2015 braindead # #",
"The above copyright notice and this permission notice shall be",
"= np.minimum(sig2 / noise_mu2, 40) if xk_prev.all() == 0: ksi",
"if dtype == np.float64: return _input, np.float64 elif dtype ==",
"voice threshold for noise update. While the voice activation detection",
"sampling rate as the one used to create the noise",
"128) / 128., _input.dtype elif _input.dtype == np.int16: return _input",
"ints. :param noise_profile: a NoiseProfile object that was created from",
"aa + (1 - aa) * np.maximum(gammak - 1, 0)",
"= np.zeros(n_fft) n_frames = len(noise) // window_size for j in",
"* len2 / np.sum(win) n_fft = 2 * window_size noise_mean",
"return _input / 32768., _input.dtype elif _input.dtype == np.int32: return",
"xk_prev / noise_mu2 + (1 - aa) * np.maximum(gammak -",
"perc / 100)) len2 = int(window_size - len1) win =",
"window_size], n_fft, axis=0)) noise_mu2 = (noise_mean / n_frames) ** 2",
"noise profile. :param wav: a speech waveform as a numpy",
"ONLY, as a numpy array of floats or ints. :param",
"WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT",
"p.len2): insign = p.win * wav[k:k + p.window_size] spec =",
"xi_w = np.fft.ifft(hw * spec, p.n_fft, axis=0) xi_w = np.real(xi_w)",
"len(noise) // window_size for j in range(0, window_size * n_frames,",
"((_input * 128) + 128).astype(np.uint8) elif dtype == np.int16: return",
"AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"int(window_size - len1) win = np.hanning(window_size) win = win *",
"to permit persons to whom the Software is # furnished",
"(1 - mu) * sig2 a = ksi / (1",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING"
] |
[
"the new session as the current one. self.current = session",
"import __project__ class Session(object): def __init__(self): self.id = None #",
"event associated to the object self.misp_event = None class Sessions(object):",
"print_info(\"Session on MISP event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on",
"sessions. # NOTE: in the future we might want to",
"entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) # Add new session to the",
"is not None and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) # Add",
"from lib.common.out import * from lib.common.objects import File from lib.core.database",
"if __project__.name: pass else: print_error(\"You must open an investigation to",
"{1}\".format(self.current.id, self.current.file.path)) def new(self, path=None, misp_event=None): if path is None",
"same file and delete it. This is to avoid #",
"must open an investigation to store files\") return session =",
"', '.join(tag.to_dict()['tag'] for tag in row[0].tag) print_info(\"Session opened on {0}\".format(path))",
"not None and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) # Add new",
"the results of the last \"find\" command. self.find = None",
"and delete it. This is to avoid # duplicates in",
"= total + 1 if path is not None: if",
"file name and row = Database().find(key='sha256', value=session.file.sha256) if row: session.file.name",
"None def is_set(self): # Check if the session has been",
"datetime from lib.common.out import * from lib.common.objects import File from",
"being analyzed. self.file = None # Timestamp of the creation",
"of the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event",
"session has been opened or not. if self.current: return True",
"will be assigned with the File object of the file",
"sessions and check whether there's another # session open on",
"= len(self.sessions) session.id = total + 1 if path is",
"misp_event if refresh: print_info(\"Session on MISP event {0} refreshed.\".format(misp_event.event_id)) else:",
"MISP event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on MISP event",
"= [] # Store the results of the last \"find\"",
"and row = Database().find(key='sha256', value=session.file.sha256) if row: session.file.name = row[0].name",
"# Open a section on the given file. session.file =",
"and misp_event is None: print_error(\"You have to open a session",
"else: print_error(\"You must open an investigation to store files\") return",
"the last \"find\" command. self.find = None def close(self): self.current",
"not None: # Loop through all existing sessions and check",
"def __init__(self): self.current = None self.sessions = [] # Store",
"self.current is not None and self.current.misp_event is not None \\",
"existing sessions and check whether there's another # session open",
"session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event associated to",
"lib.common.out import * from lib.common.objects import File from lib.core.database import",
"session.file is not None: # Loop through all existing sessions",
"session open on the same file and delete it. This",
"file and delete it. This is to avoid # duplicates",
"an history just for each of them). for entry in",
"have # unique attributes (for example, an history just for",
"the file currently # being analyzed. self.file = None #",
"file. session.file = File(path) # Try to lookup the file",
"refresh = True session.misp_event = misp_event if refresh: print_info(\"Session on",
"Loop through all existing sessions and check whether there's another",
"self.is_set() and self.current.misp_event: session.misp_event = self.current.misp_event # Open a section",
"event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on MISP event {0}.\".format(misp_event.event_id))",
"in row[0].tag) print_info(\"Session opened on {0}\".format(path)) if misp_event is not",
"remove this if sessions have # unique attributes (for example,",
"opened on MISP event {0}.\".format(misp_event.event_id)) if session.file is not None:",
"section on the given file. session.file = File(path) # Try",
"Mark the new session as the current one. self.current =",
"__init__(self): self.id = None # This will be assigned with",
"# Loop through all existing sessions and check whether there's",
"else: return False def switch(self, session): self.current = session print_info(\"Switched",
"def is_set(self): # Check if the session has been opened",
"self.sessions: if entry.file is not None and entry.file.sha256 == session.file.sha256:",
"duplicates in sessions. # NOTE: in the future we might",
"= File(path) # Try to lookup the file in the",
"If it is already present # we get file name",
"it. This is to avoid # duplicates in sessions. #",
"refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on MISP event {0}.\".format(misp_event.event_id)) if session.file",
"session.file.sha256: self.sessions.remove(entry) # Add new session to the list. self.sessions.append(session)",
"= session print_info(\"Switched to session #{0} on {1}\".format(self.current.id, self.current.file.path)) def",
"'LICENSE' for copying permission. import time import datetime from lib.common.out",
"if misp_event is not None: if self.is_set() and self.current.file: session.file",
"through all existing sessions and check whether there's another #",
"the same file and delete it. This is to avoid",
"of the file currently # being analyzed. self.file = None",
"NOTE: in the future we might want to remove this",
"delete it. This is to avoid # duplicates in sessions.",
"is_set(self): # Check if the session has been opened or",
"is None and misp_event is None: print_error(\"You have to open",
"session.file = File(path) # Try to lookup the file in",
"None self.sessions = [] # Store the results of the",
"self.current.misp_event: session.misp_event = self.current.misp_event # Open a section on the",
"there's another # session open on the same file and",
"# This will be assigned with the File object of",
"get file name and row = Database().find(key='sha256', value=session.file.sha256) if row:",
"new session as the current one. self.current = session __sessions__",
"class Sessions(object): def __init__(self): self.current = None self.sessions = []",
"just for each of them). for entry in self.sessions: if",
"session on a path or on a misp event.\") return",
"Sessions(object): def __init__(self): self.current = None self.sessions = [] #",
"refresh = False if self.current is not None and self.current.misp_event",
"def new(self, path=None, misp_event=None): if path is None and misp_event",
"is already present # we get file name and row",
"= ', '.join(tag.to_dict()['tag'] for tag in row[0].tag) print_info(\"Session opened on",
"session.id = total + 1 if path is not None:",
"whether there's another # session open on the same file",
"__project__.name: pass else: print_error(\"You must open an investigation to store",
"= True session.misp_event = misp_event if refresh: print_info(\"Session on MISP",
"# session open on the same file and delete it.",
"history just for each of them). for entry in self.sessions:",
"self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event associated to the",
"Session() total = len(self.sessions) session.id = total + 1 if",
"time import datetime from lib.common.out import * from lib.common.objects import",
"command. self.find = None def close(self): self.current = None def",
"is not None \\ and self.current.misp_event.event_id == misp_event.event_id: refresh =",
"None class Sessions(object): def __init__(self): self.current = None self.sessions =",
"None: if self.is_set() and self.current.misp_event: session.misp_event = self.current.misp_event # Open",
"session.file.tags = ', '.join(tag.to_dict()['tag'] for tag in row[0].tag) print_info(\"Session opened",
"it is already present # we get file name and",
"import * from lib.common.objects import File from lib.core.database import Database",
"as the current one. self.current = session __sessions__ = Sessions()",
"#{0} on {1}\".format(self.current.id, self.current.file.path)) def new(self, path=None, misp_event=None): if path",
"import time import datetime from lib.common.out import * from lib.common.objects",
"datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event associated to the object self.misp_event",
"Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for copying",
"{0}\".format(path)) if misp_event is not None: if self.is_set() and self.current.file:",
"file currently # being analyzed. self.file = None # Timestamp",
"for each of them). for entry in self.sessions: if entry.file",
"None and misp_event is None: print_error(\"You have to open a",
"files\") return session = Session() total = len(self.sessions) session.id =",
"open on the same file and delete it. This is",
"name and row = Database().find(key='sha256', value=session.file.sha256) if row: session.file.name =",
"self.current = session print_info(\"Switched to session #{0} on {1}\".format(self.current.id, self.current.file.path))",
"False def switch(self, session): self.current = session print_info(\"Switched to session",
"of them). for entry in self.sessions: if entry.file is not",
"session.misp_event = misp_event if refresh: print_info(\"Session on MISP event {0}",
"None \\ and self.current.misp_event.event_id == misp_event.event_id: refresh = True session.misp_event",
"list. self.sessions.append(session) # Mark the new session as the current",
"from lib.core.investigation import __project__ class Session(object): def __init__(self): self.id =",
"session): self.current = session print_info(\"Switched to session #{0} on {1}\".format(self.current.id,",
"and self.current.misp_event.event_id == misp_event.event_id: refresh = True session.misp_event = misp_event",
"if refresh: print_info(\"Session on MISP event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session",
"value=session.file.sha256) if row: session.file.name = row[0].name session.file.tags = ', '.join(tag.to_dict()['tag']",
"open an investigation to store files\") return session = Session()",
"to open a session on a path or on a",
"on a path or on a misp event.\") return if",
"path or on a misp event.\") return if __project__.name: pass",
"None and self.current.misp_event is not None \\ and self.current.misp_event.event_id ==",
"\\ and self.current.misp_event.event_id == misp_event.event_id: refresh = True session.misp_event =",
"example, an history just for each of them). for entry",
"permission. import time import datetime from lib.common.out import * from",
"print_info(\"Session opened on MISP event {0}.\".format(misp_event.event_id)) if session.file is not",
"= misp_event if refresh: print_info(\"Session on MISP event {0} refreshed.\".format(misp_event.event_id))",
"lib.core.investigation import __project__ class Session(object): def __init__(self): self.id = None",
"assigned with the File object of the file currently #",
"object of the file currently # being analyzed. self.file =",
"a section on the given file. session.file = File(path) #",
"the creation of the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') #",
"the future we might want to remove this if sessions",
"store files\") return session = Session() total = len(self.sessions) session.id",
"is not None: if self.is_set() and self.current.file: session.file = self.current.file",
"on the same file and delete it. This is to",
"class Session(object): def __init__(self): self.id = None # This will",
"has been opened or not. if self.current: return True else:",
"from lib.common.objects import File from lib.core.database import Database from lib.core.investigation",
"the file 'LICENSE' for copying permission. import time import datetime",
"to the object self.misp_event = None class Sessions(object): def __init__(self):",
"return False def switch(self, session): self.current = session print_info(\"Switched to",
"if entry.file is not None and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry)",
"on a misp event.\") return if __project__.name: pass else: print_error(\"You",
"creation of the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP",
"misp_event.event_id: refresh = True session.misp_event = misp_event if refresh: print_info(\"Session",
"this if sessions have # unique attributes (for example, an",
"Add new session to the list. self.sessions.append(session) # Mark the",
"of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE' for",
"if self.is_set() and self.current.misp_event: session.misp_event = self.current.misp_event # Open a",
"Database from lib.core.investigation import __project__ class Session(object): def __init__(self): self.id",
"is None: print_error(\"You have to open a session on a",
"__init__(self): self.current = None self.sessions = [] # Store the",
"self.current = None self.sessions = [] # Store the results",
"the given file. session.file = File(path) # Try to lookup",
"if sessions have # unique attributes (for example, an history",
"self.id = None # This will be assigned with the",
"analyzed. self.file = None # Timestamp of the creation of",
"given file. session.file = File(path) # Try to lookup the",
"on MISP event {0}.\".format(misp_event.event_id)) if session.file is not None: #",
"https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission. import",
"len(self.sessions) session.id = total + 1 if path is not",
"we might want to remove this if sessions have #",
"if path is not None: if self.is_set() and self.current.misp_event: session.misp_event",
"path is None and misp_event is None: print_error(\"You have to",
"and self.current.misp_event is not None \\ and self.current.misp_event.event_id == misp_event.event_id:",
"part of Viper - https://github.com/viper-framework/viper # See the file 'LICENSE'",
"def close(self): self.current = None def is_set(self): # Check if",
"is part of Viper - https://github.com/viper-framework/viper # See the file",
"to avoid # duplicates in sessions. # NOTE: in the",
"a session on a path or on a misp event.\")",
"in the database. If it is already present # we",
"# Mark the new session as the current one. self.current",
"all existing sessions and check whether there's another # session",
"tag in row[0].tag) print_info(\"Session opened on {0}\".format(path)) if misp_event is",
"# we get file name and row = Database().find(key='sha256', value=session.file.sha256)",
"another # session open on the same file and delete",
"misp event.\") return if __project__.name: pass else: print_error(\"You must open",
"print_info(\"Session opened on {0}\".format(path)) if misp_event is not None: if",
"new session to the list. self.sessions.append(session) # Mark the new",
"lib.common.objects import File from lib.core.database import Database from lib.core.investigation import",
"with the File object of the file currently # being",
"= self.current.file refresh = False if self.current is not None",
"is not None and self.current.misp_event is not None \\ and",
"%H:%M:%S') # MISP event associated to the object self.misp_event =",
"total + 1 if path is not None: if self.is_set()",
"self.current: return True else: return False def switch(self, session): self.current",
"row: session.file.name = row[0].name session.file.tags = ', '.join(tag.to_dict()['tag'] for tag",
"an investigation to store files\") return session = Session() total",
"opened on {0}\".format(path)) if misp_event is not None: if self.is_set()",
"self.current.file: session.file = self.current.file refresh = False if self.current is",
"This file is part of Viper - https://github.com/viper-framework/viper # See",
"entry in self.sessions: if entry.file is not None and entry.file.sha256",
"switch(self, session): self.current = session print_info(\"Switched to session #{0} on",
"in self.sessions: if entry.file is not None and entry.file.sha256 ==",
"and check whether there's another # session open on the",
"# duplicates in sessions. # NOTE: in the future we",
"row[0].tag) print_info(\"Session opened on {0}\".format(path)) if misp_event is not None:",
"# Try to lookup the file in the database. If",
"session = Session() total = len(self.sessions) session.id = total +",
"self.misp_event = None class Sessions(object): def __init__(self): self.current = None",
"close(self): self.current = None def is_set(self): # Check if the",
"session print_info(\"Switched to session #{0} on {1}\".format(self.current.id, self.current.file.path)) def new(self,",
"total = len(self.sessions) session.id = total + 1 if path",
"self.current.file.path)) def new(self, path=None, misp_event=None): if path is None and",
"open a session on a path or on a misp",
"print_error(\"You must open an investigation to store files\") return session",
"not. if self.current: return True else: return False def switch(self,",
"we get file name and row = Database().find(key='sha256', value=session.file.sha256) if",
"return if __project__.name: pass else: print_error(\"You must open an investigation",
"investigation to store files\") return session = Session() total =",
"= Session() total = len(self.sessions) session.id = total + 1",
"{0}.\".format(misp_event.event_id)) if session.file is not None: # Loop through all",
"session.misp_event = self.current.misp_event # Open a section on the given",
"the session has been opened or not. if self.current: return",
"in the future we might want to remove this if",
"future we might want to remove this if sessions have",
"None: print_error(\"You have to open a session on a path",
"session as the current one. self.current = session __sessions__ =",
"file 'LICENSE' for copying permission. import time import datetime from",
"event.\") return if __project__.name: pass else: print_error(\"You must open an",
"self.sessions.append(session) # Mark the new session as the current one.",
"None and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) # Add new session",
"session.file = self.current.file refresh = False if self.current is not",
"already present # we get file name and row =",
"the list. self.sessions.append(session) # Mark the new session as the",
"== session.file.sha256: self.sessions.remove(entry) # Add new session to the list.",
"to session #{0} on {1}\".format(self.current.id, self.current.file.path)) def new(self, path=None, misp_event=None):",
"the file in the database. If it is already present",
"lookup the file in the database. If it is already",
"currently # being analyzed. self.file = None # Timestamp of",
"= None class Sessions(object): def __init__(self): self.current = None self.sessions",
"on {0}\".format(path)) if misp_event is not None: if self.is_set() and",
"# unique attributes (for example, an history just for each",
"of the creation of the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')",
"True else: return False def switch(self, session): self.current = session",
"session #{0} on {1}\".format(self.current.id, self.current.file.path)) def new(self, path=None, misp_event=None): if",
"misp_event is None: print_error(\"You have to open a session on",
"on {1}\".format(self.current.id, self.current.file.path)) def new(self, path=None, misp_event=None): if path is",
"'.join(tag.to_dict()['tag'] for tag in row[0].tag) print_info(\"Session opened on {0}\".format(path)) if",
"self.current.misp_event.event_id == misp_event.event_id: refresh = True session.misp_event = misp_event if",
"the object self.misp_event = None class Sessions(object): def __init__(self): self.current",
"misp_event=None): if path is None and misp_event is None: print_error(\"You",
"path=None, misp_event=None): if path is None and misp_event is None:",
"= None def is_set(self): # Check if the session has",
"is not None: # Loop through all existing sessions and",
"print_info(\"Switched to session #{0} on {1}\".format(self.current.id, self.current.file.path)) def new(self, path=None,",
"have to open a session on a path or on",
"# Check if the session has been opened or not.",
"Store the results of the last \"find\" command. self.find =",
"= None # This will be assigned with the File",
"# See the file 'LICENSE' for copying permission. import time",
"if path is None and misp_event is None: print_error(\"You have",
"= None self.sessions = [] # Store the results of",
"self.current.file refresh = False if self.current is not None and",
"on MISP event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on MISP",
"new(self, path=None, misp_event=None): if path is None and misp_event is",
"\"find\" command. self.find = None def close(self): self.current = None",
"Timestamp of the creation of the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d",
"Try to lookup the file in the database. If it",
"Session(object): def __init__(self): self.id = None # This will be",
"self.find = None def close(self): self.current = None def is_set(self):",
"be assigned with the File object of the file currently",
"unique attributes (for example, an history just for each of",
"self.current.misp_event is not None \\ and self.current.misp_event.event_id == misp_event.event_id: refresh",
"{0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened on MISP event {0}.\".format(misp_event.event_id)) if",
"the session. self.created_at = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event associated",
"None # Timestamp of the creation of the session. self.created_at",
"self.is_set() and self.current.file: session.file = self.current.file refresh = False if",
"or on a misp event.\") return if __project__.name: pass else:",
"# Add new session to the list. self.sessions.append(session) # Mark",
"if row: session.file.name = row[0].name session.file.tags = ', '.join(tag.to_dict()['tag'] for",
"self.sessions = [] # Store the results of the last",
"present # we get file name and row = Database().find(key='sha256',",
"import File from lib.core.database import Database from lib.core.investigation import __project__",
"a misp event.\") return if __project__.name: pass else: print_error(\"You must",
"# Store the results of the last \"find\" command. self.find",
"MISP event {0}.\".format(misp_event.event_id)) if session.file is not None: # Loop",
"avoid # duplicates in sessions. # NOTE: in the future",
"or not. if self.current: return True else: return False def",
"This will be assigned with the File object of the",
"if session.file is not None: # Loop through all existing",
"the File object of the file currently # being analyzed.",
"self.sessions.remove(entry) # Add new session to the list. self.sessions.append(session) #",
"# MISP event associated to the object self.misp_event = None",
"__project__ class Session(object): def __init__(self): self.id = None # This",
"session to the list. self.sessions.append(session) # Mark the new session",
"None def close(self): self.current = None def is_set(self): # Check",
"Check if the session has been opened or not. if",
"None # This will be assigned with the File object",
"if the session has been opened or not. if self.current:",
"a path or on a misp event.\") return if __project__.name:",
"File object of the file currently # being analyzed. self.file",
"1 if path is not None: if self.is_set() and self.current.misp_event:",
"None: # Loop through all existing sessions and check whether",
"not None: if self.is_set() and self.current.misp_event: session.misp_event = self.current.misp_event #",
"# NOTE: in the future we might want to remove",
"path is not None: if self.is_set() and self.current.misp_event: session.misp_event =",
"if self.current: return True else: return False def switch(self, session):",
"them). for entry in self.sessions: if entry.file is not None",
"not None \\ and self.current.misp_event.event_id == misp_event.event_id: refresh = True",
"is to avoid # duplicates in sessions. # NOTE: in",
"object self.misp_event = None class Sessions(object): def __init__(self): self.current =",
"True session.misp_event = misp_event if refresh: print_info(\"Session on MISP event",
"database. If it is already present # we get file",
"= None def close(self): self.current = None def is_set(self): #",
"misp_event is not None: if self.is_set() and self.current.file: session.file =",
"import Database from lib.core.investigation import __project__ class Session(object): def __init__(self):",
"associated to the object self.misp_event = None class Sessions(object): def",
"file in the database. If it is already present #",
"entry.file is not None and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) #",
"# being analyzed. self.file = None # Timestamp of the",
"file is part of Viper - https://github.com/viper-framework/viper # See the",
"for tag in row[0].tag) print_info(\"Session opened on {0}\".format(path)) if misp_event",
"None: if self.is_set() and self.current.file: session.file = self.current.file refresh =",
"of the last \"find\" command. self.find = None def close(self):",
"return session = Session() total = len(self.sessions) session.id = total",
"= Database().find(key='sha256', value=session.file.sha256) if row: session.file.name = row[0].name session.file.tags =",
"return True else: return False def switch(self, session): self.current =",
"last \"find\" command. self.find = None def close(self): self.current =",
"= row[0].name session.file.tags = ', '.join(tag.to_dict()['tag'] for tag in row[0].tag)",
"self.current = None def is_set(self): # Check if the session",
"refresh: print_info(\"Session on MISP event {0} refreshed.\".format(misp_event.event_id)) else: print_info(\"Session opened",
"MISP event associated to the object self.misp_event = None class",
"= False if self.current is not None and self.current.misp_event is",
"[] # Store the results of the last \"find\" command.",
"* from lib.common.objects import File from lib.core.database import Database from",
"results of the last \"find\" command. self.find = None def",
"self.file = None # Timestamp of the creation of the",
"- https://github.com/viper-framework/viper # See the file 'LICENSE' for copying permission.",
"on the given file. session.file = File(path) # Try to",
"and self.current.file: session.file = self.current.file refresh = False if self.current",
"# This file is part of Viper - https://github.com/viper-framework/viper #",
"copying permission. import time import datetime from lib.common.out import *",
"print_error(\"You have to open a session on a path or",
"to remove this if sessions have # unique attributes (for",
"from lib.core.database import Database from lib.core.investigation import __project__ class Session(object):",
"row = Database().find(key='sha256', value=session.file.sha256) if row: session.file.name = row[0].name session.file.tags",
"for copying permission. import time import datetime from lib.common.out import",
"import datetime from lib.common.out import * from lib.common.objects import File",
"= self.current.misp_event # Open a section on the given file.",
"This is to avoid # duplicates in sessions. # NOTE:",
"self.current.misp_event # Open a section on the given file. session.file",
"been opened or not. if self.current: return True else: return",
"the database. If it is already present # we get",
"== misp_event.event_id: refresh = True session.misp_event = misp_event if refresh:",
"check whether there's another # session open on the same",
"Database().find(key='sha256', value=session.file.sha256) if row: session.file.name = row[0].name session.file.tags = ',",
"attributes (for example, an history just for each of them).",
"opened or not. if self.current: return True else: return False",
"else: print_info(\"Session opened on MISP event {0}.\".format(misp_event.event_id)) if session.file is",
"might want to remove this if sessions have # unique",
"False if self.current is not None and self.current.misp_event is not",
"lib.core.database import Database from lib.core.investigation import __project__ class Session(object): def",
"def __init__(self): self.id = None # This will be assigned",
"in sessions. # NOTE: in the future we might want",
"want to remove this if sessions have # unique attributes",
"if self.is_set() and self.current.file: session.file = self.current.file refresh = False",
"if self.current is not None and self.current.misp_event is not None",
"File from lib.core.database import Database from lib.core.investigation import __project__ class",
"= None # Timestamp of the creation of the session.",
"Open a section on the given file. session.file = File(path)",
"each of them). for entry in self.sessions: if entry.file is",
"and entry.file.sha256 == session.file.sha256: self.sessions.remove(entry) # Add new session to",
"def switch(self, session): self.current = session print_info(\"Switched to session #{0}",
"to lookup the file in the database. If it is",
"File(path) # Try to lookup the file in the database.",
"event {0}.\".format(misp_event.event_id)) if session.file is not None: # Loop through",
"and self.current.misp_event: session.misp_event = self.current.misp_event # Open a section on",
"to the list. self.sessions.append(session) # Mark the new session as",
"= datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S') # MISP event associated to the object",
"for entry in self.sessions: if entry.file is not None and",
"sessions have # unique attributes (for example, an history just",
"See the file 'LICENSE' for copying permission. import time import",
"not None: if self.is_set() and self.current.file: session.file = self.current.file refresh",
"to store files\") return session = Session() total = len(self.sessions)",
"session.file.name = row[0].name session.file.tags = ', '.join(tag.to_dict()['tag'] for tag in",
"(for example, an history just for each of them). for",
"not None and self.current.misp_event is not None \\ and self.current.misp_event.event_id",
"is not None: if self.is_set() and self.current.misp_event: session.misp_event = self.current.misp_event",
"pass else: print_error(\"You must open an investigation to store files\")",
"# Timestamp of the creation of the session. self.created_at =",
"+ 1 if path is not None: if self.is_set() and",
"row[0].name session.file.tags = ', '.join(tag.to_dict()['tag'] for tag in row[0].tag) print_info(\"Session"
] |
[
"tags=None, **kwargs): self.file = ffile self._workbook = Workbook(ffile, **kwargs) @property",
"до выходного файла :result: \"\"\" self._workbook.build(dst) def __setattr__(self, key, value):",
"from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для",
"Получение рабочей книги :result: рабочая книга \"\"\" return self._workbook def",
"#coding: utf-8 import xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from",
"self._workbook def build(self, dst): \"\"\" Сборка отчета :param dst: путь",
"SpreadsheetDocument): \"\"\" Обертка для отчетов в формате XLS \"\"\" def",
"def __setattr__(self, key, value): if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key,",
"dst): \"\"\" Сборка отчета :param dst: путь до выходного файла",
"if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key, value) else: super(DocumentXLS, self).__setattr__(key,",
"отчетов в формате XLS \"\"\" def __init__(self, ffile, tags=None, **kwargs):",
"**kwargs): self.file = ffile self._workbook = Workbook(ffile, **kwargs) @property def",
":param dst: путь до выходного файла :result: \"\"\" self._workbook.build(dst) def",
"\"\"\" Сборка отчета :param dst: путь до выходного файла :result:",
"\"\"\" def __init__(self, ffile, tags=None, **kwargs): self.file = ffile self._workbook",
"import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\"",
"XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для отчетов в формате",
"def __init__(self, ffile, tags=None, **kwargs): self.file = ffile self._workbook =",
"рабочей книги :result: рабочая книга \"\"\" return self._workbook def build(self,",
"__setattr__(self, key, value): if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key, value)",
"XLS \"\"\" def __init__(self, ffile, tags=None, **kwargs): self.file = ffile",
"key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key, value) else: super(DocumentXLS, self).__setattr__(key, value)",
"книги :result: рабочая книга \"\"\" return self._workbook def build(self, dst):",
"xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook",
"\"\"\" Обертка для отчетов в формате XLS \"\"\" def __init__(self,",
"формате XLS \"\"\" def __init__(self, ffile, tags=None, **kwargs): self.file =",
"файла :result: \"\"\" self._workbook.build(dst) def __setattr__(self, key, value): if key",
"key, value): if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key, value) else:",
"для отчетов в формате XLS \"\"\" def __init__(self, ffile, tags=None,",
"= ffile self._workbook = Workbook(ffile, **kwargs) @property def workbook(self): \"\"\"",
"simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для отчетов",
"workbook(self): \"\"\" Получение рабочей книги :result: рабочая книга \"\"\" return",
"**kwargs) @property def workbook(self): \"\"\" Получение рабочей книги :result: рабочая",
"from simple_report.xls.workbook import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument,",
"книга \"\"\" return self._workbook def build(self, dst): \"\"\" Сборка отчета",
"import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для отчетов в",
"import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook from simple_report.xls.output_options import",
"from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook from",
"<filename>src/simple_report/xls/document.py #coding: utf-8 import xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument",
"= Workbook(ffile, **kwargs) @property def workbook(self): \"\"\" Получение рабочей книги",
"self._workbook.build(dst) def __setattr__(self, key, value): if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook,",
"def workbook(self): \"\"\" Получение рабочей книги :result: рабочая книга \"\"\"",
"self._workbook = Workbook(ffile, **kwargs) @property def workbook(self): \"\"\" Получение рабочей",
"\"\"\" return self._workbook def build(self, dst): \"\"\" Сборка отчета :param",
"Обертка для отчетов в формате XLS \"\"\" def __init__(self, ffile,",
"ffile, tags=None, **kwargs): self.file = ffile self._workbook = Workbook(ffile, **kwargs)",
":result: рабочая книга \"\"\" return self._workbook def build(self, dst): \"\"\"",
"utf-8 import xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook",
"рабочая книга \"\"\" return self._workbook def build(self, dst): \"\"\" Сборка",
"simple_report.xls.workbook import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument):",
"путь до выходного файла :result: \"\"\" self._workbook.build(dst) def __setattr__(self, key,",
"DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для отчетов в формате XLS \"\"\"",
"class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка для отчетов в формате XLS",
"Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class DocumentXLS(BaseDocument, SpreadsheetDocument): \"\"\" Обертка",
"self.file = ffile self._workbook = Workbook(ffile, **kwargs) @property def workbook(self):",
":result: \"\"\" self._workbook.build(dst) def __setattr__(self, key, value): if key in",
"выходного файла :result: \"\"\" self._workbook.build(dst) def __setattr__(self, key, value): if",
"value): if key in XSL_OUTPUT_SETTINGS: setattr(self._workbook, key, value) else: super(DocumentXLS,",
"simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook from simple_report.xls.output_options",
"__init__(self, ffile, tags=None, **kwargs): self.file = ffile self._workbook = Workbook(ffile,",
"@property def workbook(self): \"\"\" Получение рабочей книги :result: рабочая книга",
"\"\"\" Получение рабочей книги :result: рабочая книга \"\"\" return self._workbook",
"def build(self, dst): \"\"\" Сборка отчета :param dst: путь до",
"SpreadsheetDocument from simple_report.xls.workbook import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS class",
"Workbook(ffile, **kwargs) @property def workbook(self): \"\"\" Получение рабочей книги :result:",
"build(self, dst): \"\"\" Сборка отчета :param dst: путь до выходного",
"отчета :param dst: путь до выходного файла :result: \"\"\" self._workbook.build(dst)",
"ffile self._workbook = Workbook(ffile, **kwargs) @property def workbook(self): \"\"\" Получение",
"dst: путь до выходного файла :result: \"\"\" self._workbook.build(dst) def __setattr__(self,",
"import xlrd from simple_report.core.document_wrap import BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import",
"BaseDocument, SpreadsheetDocument from simple_report.xls.workbook import Workbook from simple_report.xls.output_options import XSL_OUTPUT_SETTINGS",
"в формате XLS \"\"\" def __init__(self, ffile, tags=None, **kwargs): self.file",
"\"\"\" self._workbook.build(dst) def __setattr__(self, key, value): if key in XSL_OUTPUT_SETTINGS:",
"return self._workbook def build(self, dst): \"\"\" Сборка отчета :param dst:",
"Сборка отчета :param dst: путь до выходного файла :result: \"\"\""
] |
[
"test_train_ids = \"aa\" test_tag = \"bb\" params = dict(train_ids=test_train_ids, tag=test_tag)",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"== '405 Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor,",
"text = 'Test Message' # NotFound def get_metadata_list(train_ids, tag): raise",
"handling http exception error method not allowed.\"\"\" scalars_processor.logger = MockLogger",
"response = client.get(url) assert response.status_code == 500 response = response.get_json()",
"def get_metadata_list(train_ids, tag): raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list",
"# # Licensed under the Apache License, Version 2.0 (the",
"compliance with the License. # You may obtain a copy",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"2.0 (the \"License\"); # you may not use this file",
"agreed to in writing, software # distributed under the License",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Unless required by applicable law or agreed to in writing,",
"from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler:",
"get_metadata_list(train_ids, tag): raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids",
"= client.get(url) assert response.status_code == 404 response = response.get_json() assert",
"== '404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client):",
"mock_scalar_processor, client): \"\"\"Test handling http exception error method not allowed.\"\"\"",
"response.get_json() assert response['error_code'] == '50540000' assert response['error_msg'] == 'System error.'",
"distributed under the License is distributed on an \"AS IS\"",
"raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\"",
"Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling",
"import TRAIN_ROUTES from ..mock import MockLogger from ....utils.tools import get_url",
"exception error not found.\"\"\" scalars_processor.logger = MockLogger text = 'Test",
"= \"aa\" test_tag = \"bb\" params = dict(train_ids=test_train_ids, tag=test_tag) url",
"MockLogger text = 'Test Message' # MethodNotAllowed def get_metadata_list(train_ids, tag):",
"Technologies Co., Ltd # # Licensed under the Apache License,",
"the specific language governing permissions and # limitations under the",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"405 response = response.get_json() assert response['error_code'] == '50545002' assert response['error_msg']",
"test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling http exception error method other",
"Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling http",
"express or implied. # See the License for the specific",
"applicable law or agreed to in writing, software # distributed",
"# MethodNotAllowed def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect",
"get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 405 response",
"except in compliance with the License. # You may obtain",
"response.status_code == 405 response = response.get_json() assert response['error_code'] == '50545002'",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"class TestErrorHandler: \"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self,",
"visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle",
"params) response = client.get(url) assert response.status_code == 404 response =",
"TestErrorHandler: \"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor,",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"....utils.tools import get_url from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import",
"def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle http exception error not",
"from unittest.mock import patch from werkzeug.exceptions import MethodNotAllowed, NotFound from",
"and # limitations under the License. # ============================================================================ \"\"\" Function:",
"not use this file except in compliance with the License.",
"= response.get_json() assert response['error_code'] == '50545002' assert response['error_msg'] == '405",
"http exception error method not allowed.\"\"\" scalars_processor.logger = MockLogger text",
"not allowed.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' #",
"raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\"",
"response = response.get_json() assert response['error_code'] == '50545001' assert response['error_msg'] ==",
"pytest tests/ut/datavisual \"\"\" from unittest.mock import patch from werkzeug.exceptions import",
"= client.get(url) assert response.status_code == 405 response = response.get_json() assert",
"permissions and # limitations under the License. # ============================================================================ \"\"\"",
"writing, software # distributed under the License is distributed on",
"import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler: \"\"\"Test train",
"'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling http exception error",
"in writing, software # distributed under the License is distributed",
"response.get_json() assert response['error_code'] == '50545001' assert response['error_msg'] == '404 Not",
"= 'Test Message' # Other errors def get_metadata_list(train_ids, tag): raise",
"you may not use this file except in compliance with",
"method not allowed.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message'",
"'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle http exception error",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
"get_url from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class",
"500 response = response.get_json() assert response['error_code'] == '50540000' assert response['error_msg']",
"Message' # NotFound def get_metadata_list(train_ids, tag): raise NotFound(\"%s\" % text)",
"== 405 response = response.get_json() assert response['error_code'] == '50545002' assert",
"'405 Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client):",
"Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling http",
"error not found.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message'",
"tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code",
"use this file except in compliance with the License. #",
"= MockLogger text = 'Test Message' # NotFound def get_metadata_list(train_ids,",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"handle http exception error not found.\"\"\" scalars_processor.logger = MockLogger text",
"============================================================================ \"\"\" Function: Test error handler. Usage: pytest tests/ut/datavisual \"\"\"",
"found.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' # NotFound",
"response.status_code == 404 response = response.get_json() assert response['error_code'] == '50545001'",
"= get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 404",
"== 500 response = response.get_json() assert response['error_code'] == '50540000' assert",
"response = response.get_json() assert response['error_code'] == '50540000' assert response['error_msg'] ==",
"the License. # ============================================================================ \"\"\" Function: Test error handler. Usage:",
"unittest.mock import patch from werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest",
"tag): raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids =",
"text = 'Test Message' # Other errors def get_metadata_list(train_ids, tag):",
"response['error_msg'] == '404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor,",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"client.get(url) assert response.status_code == 404 response = response.get_json() assert response['error_code']",
"mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler: \"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor,",
"License. # ============================================================================ \"\"\" Function: Test error handler. Usage: pytest",
"Ltd # # Licensed under the Apache License, Version 2.0",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"response['error_code'] == '50545001' assert response['error_msg'] == '404 Not Found.' @patch.object(ScalarsProcessor,",
"'50545002' assert response['error_msg'] == '405 Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list')",
"\"bb\" params = dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response",
"or implied. # See the License for the specific language",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"% text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag =",
"from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import MockLogger from ....utils.tools",
"License. # You may obtain a copy of the License",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"License, Version 2.0 (the \"License\"); # you may not use",
"== 404 response = response.get_json() assert response['error_code'] == '50545001' assert",
"= MockLogger text = 'Test Message' # Other errors def",
"# You may obtain a copy of the License at",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"= response.get_json() assert response['error_code'] == '50540000' assert response['error_msg'] == 'System",
"MockLogger text = 'Test Message' # NotFound def get_metadata_list(train_ids, tag):",
"errors def get_metadata_list(train_ids, tag): raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect =",
"get_metadata_list test_train_ids = \"aa\" test_tag = \"bb\" params = dict(train_ids=test_train_ids,",
"under the License is distributed on an \"AS IS\" BASIS,",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"License for the specific language governing permissions and # limitations",
"assert response.status_code == 405 response = response.get_json() assert response['error_code'] ==",
"MockLogger text = 'Test Message' # Other errors def get_metadata_list(train_ids,",
"client.get(url) assert response.status_code == 500 response = response.get_json() assert response['error_code']",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"handling http exception error method other errors.\"\"\" scalars_processor.logger = MockLogger",
"dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert",
"test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling http exception error method not",
"\"\"\" Function: Test error handler. Usage: pytest tests/ut/datavisual \"\"\" from",
"# limitations under the License. # ============================================================================ \"\"\" Function: Test",
"# ============================================================================ \"\"\" Function: Test error handler. Usage: pytest tests/ut/datavisual",
"..mock import MockLogger from ....utils.tools import get_url from mindinsight.datavisual.processors import",
"= get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 500",
"\"\"\" from unittest.mock import patch from werkzeug.exceptions import MethodNotAllowed, NotFound",
"...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import MockLogger from ....utils.tools import",
"= 'Test Message' # NotFound def get_metadata_list(train_ids, tag): raise NotFound(\"%s\"",
"def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list",
"mock_scalar_processor, client): \"\"\"Test handling http exception error method other errors.\"\"\"",
"KeyError(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag",
"error handler. Usage: pytest tests/ut/datavisual \"\"\" from unittest.mock import patch",
"handler. Usage: pytest tests/ut/datavisual \"\"\" from unittest.mock import patch from",
"\"aa\" test_tag = \"bb\" params = dict(train_ids=test_train_ids, tag=test_tag) url =",
"Copyright 2019 Huawei Technologies Co., Ltd # # Licensed under",
"get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids",
"import ScalarsProcessor class TestErrorHandler: \"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list')",
"MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag",
"response['error_code'] == '50545002' assert response['error_msg'] == '405 Method Not Allowed.'",
"assert response.status_code == 500 response = response.get_json() assert response['error_code'] ==",
"MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import MockLogger",
"import get_url from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor",
"the License for the specific language governing permissions and #",
"Test error handler. Usage: pytest tests/ut/datavisual \"\"\" from unittest.mock import",
"get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 404 response",
"(the \"License\"); # you may not use this file except",
"client): \"\"\"Test handle http exception error not found.\"\"\" scalars_processor.logger =",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"NotFound def get_metadata_list(train_ids, tag): raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect =",
"# you may not use this file except in compliance",
"limitations under the License. # ============================================================================ \"\"\" Function: Test error",
"\"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client):",
"either express or implied. # See the License for the",
"== '50545001' assert response['error_msg'] == '404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list')",
"= 'Test Message' # MethodNotAllowed def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\"",
"get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 500 response",
"@patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle http exception",
"= MockLogger text = 'Test Message' # MethodNotAllowed def get_metadata_list(train_ids,",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"== '50545002' assert response['error_msg'] == '405 Method Not Allowed.' @patch.object(ScalarsProcessor,",
"Message' # MethodNotAllowed def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" % text)",
"tests/ut/datavisual \"\"\" from unittest.mock import patch from werkzeug.exceptions import MethodNotAllowed,",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"\"\"\"Test handle http exception error not found.\"\"\" scalars_processor.logger = MockLogger",
"@patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling http exception",
"params) response = client.get(url) assert response.status_code == 405 response =",
"the License is distributed on an \"AS IS\" BASIS, #",
"def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling http exception error method",
"params = dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response =",
"http exception error method other errors.\"\"\" scalars_processor.logger = MockLogger text",
"in compliance with the License. # You may obtain a",
"MockLogger from ....utils.tools import get_url from mindinsight.datavisual.processors import scalars_processor from",
"MethodNotAllowed def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" % text) mock_scalar_processor.side_effect =",
"other errors.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' #",
"software # distributed under the License is distributed on an",
"mock_scalar_processor, client): \"\"\"Test handle http exception error not found.\"\"\" scalars_processor.logger",
"Function: Test error handler. Usage: pytest tests/ut/datavisual \"\"\" from unittest.mock",
"client.get(url) assert response.status_code == 405 response = response.get_json() assert response['error_code']",
"= client.get(url) assert response.status_code == 500 response = response.get_json() assert",
"import patch from werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import",
"assert response['error_code'] == '50545002' assert response['error_msg'] == '405 Method Not",
"test_tag = \"bb\" params = dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'],",
"Huawei Technologies Co., Ltd # # Licensed under the Apache",
"# # Unless required by applicable law or agreed to",
"import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import",
"# Other errors def get_metadata_list(train_ids, tag): raise KeyError(\"%s\" % text)",
"test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle http exception error not found.\"\"\"",
"error method other errors.\"\"\" scalars_processor.logger = MockLogger text = 'Test",
"Message' # Other errors def get_metadata_list(train_ids, tag): raise KeyError(\"%s\" %",
"not found.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' #",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test handle http",
"\"\"\"Test handling http exception error method other errors.\"\"\" scalars_processor.logger =",
"= dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url)",
"http exception error not found.\"\"\" scalars_processor.logger = MockLogger text =",
"client): \"\"\"Test handling http exception error method other errors.\"\"\" scalars_processor.logger",
"Version 2.0 (the \"License\"); # you may not use this",
"response.status_code == 500 response = response.get_json() assert response['error_code'] == '50540000'",
"NotFound(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag",
"law or agreed to in writing, software # distributed under",
"text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag = \"bb\"",
"mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler: \"\"\"Test",
"404 response = response.get_json() assert response['error_code'] == '50545001' assert response['error_msg']",
"Co., Ltd # # Licensed under the Apache License, Version",
"= \"bb\" params = dict(train_ids=test_train_ids, tag=test_tag) url = get_url(TRAIN_ROUTES['scalar_metadata'], params)",
"NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock import MockLogger from",
"raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\"",
"error method not allowed.\"\"\" scalars_processor.logger = MockLogger text = 'Test",
"allowed.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' # MethodNotAllowed",
"from ..mock import MockLogger from ....utils.tools import get_url from mindinsight.datavisual.processors",
"= response.get_json() assert response['error_code'] == '50545001' assert response['error_msg'] == '404",
"from werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from",
"implied. # See the License for the specific language governing",
"url = get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code ==",
"text = 'Test Message' # MethodNotAllowed def get_metadata_list(train_ids, tag): raise",
"@patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling http exception",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"\"License\"); # you may not use this file except in",
"'50545001' assert response['error_msg'] == '404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def",
"'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test handling http exception error",
"assert response['error_code'] == '50545001' assert response['error_msg'] == '404 Not Found.'",
"tag): raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids =",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"assert response['error_msg'] == '404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self,",
"by applicable law or agreed to in writing, software #",
"# distributed under the License is distributed on an \"AS",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"client): \"\"\"Test handling http exception error method not allowed.\"\"\" scalars_processor.logger",
"response = response.get_json() assert response['error_code'] == '50545002' assert response['error_msg'] ==",
"def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling http exception error method",
"may obtain a copy of the License at # #",
"# Unless required by applicable law or agreed to in",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler: \"\"\"Test train visual api.\"\"\"",
"= get_metadata_list test_train_ids = \"aa\" test_tag = \"bb\" params =",
"werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES from ..mock",
"assert response.status_code == 404 response = response.get_json() assert response['error_code'] ==",
"response = client.get(url) assert response.status_code == 405 response = response.get_json()",
"exception error method other errors.\"\"\" scalars_processor.logger = MockLogger text =",
"params) response = client.get(url) assert response.status_code == 500 response =",
"the License. # You may obtain a copy of the",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for the specific language governing permissions and # limitations under",
"TRAIN_ROUTES from ..mock import MockLogger from ....utils.tools import get_url from",
"response['error_msg'] == '405 Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self,",
"scalars_processor.logger = MockLogger text = 'Test Message' # Other errors",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"to in writing, software # distributed under the License is",
"mock_scalar_processor.side_effect = get_metadata_list test_train_ids = \"aa\" test_tag = \"bb\" params",
"response = client.get(url) assert response.status_code == 404 response = response.get_json()",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"# Copyright 2019 Huawei Technologies Co., Ltd # # Licensed",
"# See the License for the specific language governing permissions",
"scalars_processor from mindinsight.datavisual.processors.scalars_processor import ScalarsProcessor class TestErrorHandler: \"\"\"Test train visual",
"'Test Message' # NotFound def get_metadata_list(train_ids, tag): raise NotFound(\"%s\" %",
"def get_metadata_list(train_ids, tag): raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list",
"You may obtain a copy of the License at #",
"import MockLogger from ....utils.tools import get_url from mindinsight.datavisual.processors import scalars_processor",
"2019 Huawei Technologies Co., Ltd # # Licensed under the",
"# NotFound def get_metadata_list(train_ids, tag): raise NotFound(\"%s\" % text) mock_scalar_processor.side_effect",
"language governing permissions and # limitations under the License. #",
"exception error method not allowed.\"\"\" scalars_processor.logger = MockLogger text =",
"may not use this file except in compliance with the",
"or agreed to in writing, software # distributed under the",
"train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_not_found(self, mock_scalar_processor, client): \"\"\"Test",
"ScalarsProcessor class TestErrorHandler: \"\"\"Test train visual api.\"\"\" @patch.object(ScalarsProcessor, 'get_metadata_list') def",
"'404 Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test",
"response.get_json() assert response['error_code'] == '50545002' assert response['error_msg'] == '405 Method",
"Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_other_errors(self, mock_scalar_processor, client): \"\"\"Test",
"required by applicable law or agreed to in writing, software",
"under the License. # ============================================================================ \"\"\" Function: Test error handler.",
"method other errors.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message'",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"Other errors def get_metadata_list(train_ids, tag): raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect",
"scalars_processor.logger = MockLogger text = 'Test Message' # MethodNotAllowed def",
"tag): raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids =",
"with the License. # You may obtain a copy of",
"Usage: pytest tests/ut/datavisual \"\"\" from unittest.mock import patch from werkzeug.exceptions",
"this file except in compliance with the License. # You",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"scalars_processor.logger = MockLogger text = 'Test Message' # NotFound def",
"Not Found.' @patch.object(ScalarsProcessor, 'get_metadata_list') def test_handle_http_exception_error_method_not_allowed(self, mock_scalar_processor, client): \"\"\"Test handling",
"'Test Message' # Other errors def get_metadata_list(train_ids, tag): raise KeyError(\"%s\"",
"errors.\"\"\" scalars_processor.logger = MockLogger text = 'Test Message' # Other",
"governing permissions and # limitations under the License. # ============================================================================",
"\"\"\"Test handling http exception error method not allowed.\"\"\" scalars_processor.logger =",
"assert response['error_msg'] == '405 Method Not Allowed.' @patch.object(ScalarsProcessor, 'get_metadata_list') def",
"= get_url(TRAIN_ROUTES['scalar_metadata'], params) response = client.get(url) assert response.status_code == 405",
"get_metadata_list(train_ids, tag): raise KeyError(\"%s\" % text) mock_scalar_processor.side_effect = get_metadata_list test_train_ids",
"'Test Message' # MethodNotAllowed def get_metadata_list(train_ids, tag): raise MethodNotAllowed(\"%s\" %",
"patch from werkzeug.exceptions import MethodNotAllowed, NotFound from ...backend.datavisual.conftest import TRAIN_ROUTES",
"from ....utils.tools import get_url from mindinsight.datavisual.processors import scalars_processor from mindinsight.datavisual.processors.scalars_processor"
] |
[
"number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build',",
"index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None,",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1,",
"serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST =",
"import message as _message from google.protobuf import reflection as _reflection",
"\\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None,",
"= _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id',",
"cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1,",
"serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] =",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4,",
"_sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__'",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error',",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9,",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data',",
"import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from",
"_message from google.protobuf import reflection as _reflection from google.protobuf import",
"_descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None,",
"= _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,),",
"_reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2' #",
"name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3',",
"the protocol buffer compiler. DO NOT EDIT! # source: cancel_build.proto",
"nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58,",
"serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False,",
"_descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"= _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2'",
"= _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' :",
"], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None,",
"by the protocol buffer compiler. DO NOT EDIT! # source:",
"_CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper) }) _sym_db.RegisterMessage(CancelResponseWrapper) # @@protoc_insertion_point(module_scope)",
"syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor(",
"(lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf",
"package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') ,",
"oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper',",
"serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None,",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False,",
"type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"(_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper)",
"NOT EDIT! # source: cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda",
"number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"_CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor(",
"oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] =",
"# source: cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or",
") _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[",
"_CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR)",
"'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), {",
"_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import",
"import reflection as _reflection from google.protobuf import symbol_database as _symbol_database",
"as _descriptor from google.protobuf import message as _message from google.protobuf",
"name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None,",
"nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93,",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3,",
"cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1,",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1,",
"index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False,",
"}) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER,",
"as _message from google.protobuf import reflection as _reflection from google.protobuf",
"{ 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper) })",
", dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None,",
"from google.protobuf import message as _message from google.protobuf import reflection",
"_symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import empty_pb2",
"_reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' #",
"_CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST,",
"# Generated by the protocol buffer compiler. DO NOT EDIT!",
"full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None,",
"# @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR'",
"enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91,",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3,",
"<reponame>easyopsapis/easyops-api-python<filename>pipeline_sdk/api/build/cancel_build_pb2.py # -*- coding: utf-8 -*- # Generated by the",
"(lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as",
"filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5,",
"_descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id',",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ],",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ],",
"DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest',",
"(_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest)",
"import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from",
"file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False,",
"utf-8 -*- # Generated by the protocol buffer compiler. DO",
"google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest =",
"import descriptor as _descriptor from google.protobuf import message as _message",
"as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import",
"_descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04",
"extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error',",
"filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9,",
"Generated by the protocol buffer compiler. DO NOT EDIT! #",
"x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor",
"name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0,",
"message as _message from google.protobuf import reflection as _reflection from",
"_reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db",
"fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False,",
"label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR),",
"full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data',",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None,",
"= _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2'",
"symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf",
"coding: utf-8 -*- # Generated by the protocol buffer compiler.",
"google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01",
"extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper',",
"-*- # Generated by the protocol buffer compiler. DO NOT",
"descriptor as _descriptor from google.protobuf import message as _message from",
"_descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"= google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest",
"google.protobuf import descriptor as _descriptor from google.protobuf import message as",
"containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1,",
"import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3',",
"cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None,",
"compiler. DO NOT EDIT! # source: cancel_build.proto import sys _b=sys.version_info[0]<3",
"x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import",
"_descriptor from google.protobuf import message as _message from google.protobuf import",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9,",
"google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default()",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9,",
"reflection as _reflection from google.protobuf import symbol_database as _symbol_database #",
"as _reflection from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports)",
"_descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code',",
"serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type",
"_sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__'",
"_descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'),",
"full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1,",
"serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1,",
"from google.protobuf import reflection as _reflection from google.protobuf import symbol_database",
"google.protobuf import reflection as _reflection from google.protobuf import symbol_database as",
"and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor",
"_descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0,",
"index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None,",
"type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,",
"enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204,",
"extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11, cpp_type=10,",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ],",
"_CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper =",
"name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3')",
"default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[",
"_CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor(",
"{ 'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) })",
"CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR' : _CANCELREQUEST, '__module__' :",
"'__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper',",
"'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper) }) _sym_db.RegisterMessage(CancelResponseWrapper)",
"full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1,",
"number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper']",
"_symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor(",
"_CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), {",
"], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ],",
"\\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor(",
": _CANCELRESPONSEWRAPPER, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelResponseWrapper) }) _sym_db.RegisterMessage(CancelResponseWrapper) #",
": _CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper",
"syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY",
"index=0, number=1, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"has_default_value=False, default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor(",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[], enum_types=[",
") _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER",
"default_value=0, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain',",
"source: cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda",
"= _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='code',",
"protocol buffer compiler. DO NOT EDIT! # source: cancel_build.proto import",
"], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, )",
"@@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2",
"name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"# @@protoc_insertion_point(imports) _sym_db = _symbol_database.Default() from google.protobuf import empty_pb2 as",
"serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER = _descriptor.Descriptor( name='CancelResponseWrapper', full_name='build.CancelResponseWrapper', filename=None, file=DESCRIPTOR,",
"from google.protobuf import symbol_database as _symbol_database # @@protoc_insertion_point(imports) _sym_db =",
"containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2,",
"name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0,",
"CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' : _CANCELRESPONSEWRAPPER, '__module__' :",
"full_name='build.CancelResponseWrapper.codeExplain', index=1, number=2, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None,",
"= _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03",
"\\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR,",
"cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))",
"is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER =",
"EDIT! # source: cancel_build.proto import sys _b=sys.version_info[0]<3 and (lambda x:x)",
"extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest']",
"serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, ) _CANCELRESPONSEWRAPPER",
": 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,),",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2,",
"'DESCRIPTOR' : _CANCELREQUEST, '__module__' : 'cancel_build_pb2' # @@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest)",
"# -*- coding: utf-8 -*- # Generated by the protocol",
"from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto',",
"fields=[ _descriptor.FieldDescriptor( name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False,",
"sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9,",
"= _symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR =",
"], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type = google_dot_protobuf_dot_empty__pb2._EMPTY DESCRIPTOR.message_types_by_name['CancelRequest'] = _CANCELREQUEST",
"DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02",
"is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=93, serialized_end=204, ) _CANCELRESPONSEWRAPPER.fields_by_name['data'].message_type =",
"serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST",
"has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ],",
"is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='data', full_name='build.CancelResponseWrapper.data', index=3, number=4, type=11,",
"default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[",
"file=DESCRIPTOR, containing_type=None, fields=[ _descriptor.FieldDescriptor( name='build_id', full_name='build.CancelRequest.build_id', index=0, number=1, type=9, cpp_type=9,",
"google.protobuf import message as _message from google.protobuf import reflection as",
"as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01",
"syntax='proto3', serialized_options=None, serialized_pb=_b('\\n\\x12\\x63\\x61ncel_build.proto\\x12\\x05\\x62uild\\x1a\\x1bgoogle/protobuf/empty.proto\\\"!\\n\\rCancelRequest\\x12\\x10\\n\\x08\\x62uild_id\\x18\\x01 \\x01(\\t\\\"o\\n\\x15\\x43\\x61ncelResponseWrapper\\x12\\x0c\\n\\x04\\x63ode\\x18\\x01 \\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,])",
"DESCRIPTOR.message_types_by_name['CancelResponseWrapper'] = _CANCELRESPONSEWRAPPER _sym_db.RegisterFileDescriptor(DESCRIPTOR) CancelRequest = _reflection.GeneratedProtocolMessageType('CancelRequest', (_message.Message,), { 'DESCRIPTOR'",
"name='code', full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None,",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain', index=1,",
"buffer compiler. DO NOT EDIT! # source: cancel_build.proto import sys",
"has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor(",
"message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), _descriptor.FieldDescriptor( name='codeExplain', full_name='build.CancelResponseWrapper.codeExplain',",
"], extensions=[ ], nested_types=[], enum_types=[ ], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[],",
"name='error', full_name='build.CancelResponseWrapper.error', index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None,",
"\\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest',",
"], serialized_options=None, is_extendable=False, syntax='proto3', extension_ranges=[], oneofs=[ ], serialized_start=58, serialized_end=91, )",
"@@protoc_insertion_point(class_scope:build.CancelRequest) }) _sym_db.RegisterMessage(CancelRequest) CancelResponseWrapper = _reflection.GeneratedProtocolMessageType('CancelResponseWrapper', (_message.Message,), { 'DESCRIPTOR' :",
"\\x01(\\x05\\x12\\x13\\n\\x0b\\x63odeExplain\\x18\\x02 \\x01(\\t\\x12\\r\\n\\x05\\x65rror\\x18\\x03 \\x01(\\t\\x12$\\n\\x04\\x64\\x61ta\\x18\\x04 \\x01(\\x0b\\x32\\x16.google.protobuf.Emptyb\\x06proto3') , dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest',",
"number=4, type=11, cpp_type=10, label=1, has_default_value=False, default_value=None, message_type=None, enum_type=None, containing_type=None, is_extension=False,",
"or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from",
"dependencies=[google_dot_protobuf_dot_empty__pb2.DESCRIPTOR,]) _CANCELREQUEST = _descriptor.Descriptor( name='CancelRequest', full_name='build.CancelRequest', filename=None, file=DESCRIPTOR, containing_type=None, fields=[",
"DO NOT EDIT! # source: cancel_build.proto import sys _b=sys.version_info[0]<3 and",
"enum_type=None, containing_type=None, is_extension=False, extension_scope=None, serialized_options=None, file=DESCRIPTOR), ], extensions=[ ], nested_types=[],",
"index=2, number=3, type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None,",
"from google.protobuf import descriptor as _descriptor from google.protobuf import message",
"_sym_db = _symbol_database.Default() from google.protobuf import empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR",
"empty_pb2 as google_dot_protobuf_dot_empty__pb2 DESCRIPTOR = _descriptor.FileDescriptor( name='cancel_build.proto', package='build', syntax='proto3', serialized_options=None,",
"-*- coding: utf-8 -*- # Generated by the protocol buffer",
"full_name='build.CancelResponseWrapper.code', index=0, number=1, type=5, cpp_type=1, label=1, has_default_value=False, default_value=0, message_type=None, enum_type=None,",
"type=9, cpp_type=9, label=1, has_default_value=False, default_value=_b(\"\").decode('utf-8'), message_type=None, enum_type=None, containing_type=None, is_extension=False, extension_scope=None,"
] |
[
"where you can load them. ''' try: print('Model is loading...')",
"Estimated yaw (in degrees). name: \"angle_p_fc\", shape: [1, 1] -",
"format: name: \"angle_y_fc\", shape: [1, 1] - Estimated yaw (in",
"fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net, self.device)",
"self.input_shape = self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise..",
"== 0: # results = infer.outputs[self.output_name] # print(results) # print(self.input_name)",
"fix, Failed.') else: print('Check the extension path.') self.net_exec = self.core.load_network(network=self.net,",
"IECore import numpy as np import os import cv2 import",
"= self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device) not_supported = [layer for",
"been provided just to give you an idea of how",
"any Plugins, this is where you can load them. '''",
"check_model(self): ''' Check - initialise the model ''' try: self.model",
"or make any changes to it. This has been provided",
"layer not in supported] if len(not_supported) == 0: print('***Quick fix,",
"print('HeadPose predict..') pre_image = self.preprocess_input(self.image) input_name = self.input_name input_dict =",
"''' This method is for loading the model to the",
"== 'CPU': print('Unsuported', not_supported) if not self.extensions == None: print('***Quick",
"= [] print('PreOutput-headpose..') # print(outputs) object_list.append(outputs['angle_y_fc'].tolist()[0][0]) object_list.append(outputs['angle_p_fc'].tolist()[0][0]) object_list.append(outputs['angle_r_fc'].tolist()[0][0]) return object_list",
"0: # results = infer.outputs[self.output_name] # print(results) # print(self.input_name) #",
"predict(self, image): ''' This method is meant for running predictions",
"This method is meant for running predictions on the input",
"name: \"angle_p_fc\", shape: [1, 1] - Estimated pitch (in degrees).",
"Initialise the network. Have you enterred the correct model path?\")",
"just to give you an idea of how to structure",
"self.core.load_network(network=self.net, device_name=self.device) except Exception as e: raise('Something is wrong.. ~debug",
"W - image width ''' image = cv2.resize(image, (self.input_shape[3], self.input_shape[2]))",
"with input and output values..') def load_model(self): ''' This method",
"# self.output_name = next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise..",
"degrees). ''' object_list = [] print('PreOutput-headpose..') # print(outputs) object_list.append(outputs['angle_y_fc'].tolist()[0][0]) object_list.append(outputs['angle_p_fc'].tolist()[0][0])",
"self.extensions = extensions # self.check_model() # try: # self.input_name =",
"the Head Pose Estimation Model. ''' def __init__(self, model_name, device='CPU',",
"and output values..') def predict(self, image): ''' This method is",
"requires any Plugins, this is where you can load them.",
"cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image = image.transpose((2, 0, 1)) image =",
"self.image = image print('HeadPose predict..') pre_image = self.preprocess_input(self.image) input_name =",
"meant for running predictions on the input image. ''' self.image",
"name: \"angle_y_fc\", shape: [1, 1] - Estimated yaw (in degrees).",
"outputs = self.preprocess_output(results) # if status == 0: # results",
"def preprocess_output(self, outputs): ''' Output layer names in Inference Engine",
"= self.net_exec.start_async(request_id=0, inputs=input_dict) # status = infer.wait() results = self.net_exec.infer(input_dict)",
"# infer = self.net_exec.start_async(request_id=0, inputs=input_dict) # status = infer.wait() results",
"# except Exception as e: # raise ValueError('Something is wrong",
"load model~') try: self.input_name = next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name",
"# print(self.input_name) # outputs = self.preprocess_output(results) return outputs def check_model(self):",
"Estimation Model. ''' def __init__(self, model_name, device='CPU', extensions=None): self.model_weights =",
"for loading the model to the device specified by the",
"added') self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net, self.device) not_supported = [layer",
"self.net_exec.start_async(request_id=0, inputs=input_dict) # status = infer.wait() results = self.net_exec.infer(input_dict) outputs",
"results = infer.outputs[self.output_name] # print(results) # print(self.input_name) # outputs =",
"(in degrees). name: \"angle_p_fc\", shape: [1, 1] - Estimated pitch",
"except Exception as e: # raise ValueError('Something is wrong with",
"sys class Model_HeadPose: ''' Class for the Head Pose Estimation",
"image.transpose((2, 0, 1)) image = image.reshape(1, *image.shape) return image def",
"to use it as-is or make any changes to it.",
"an idea of how to structure your model class. '''",
"H - image height W - image width ''' image",
"- Estimated yaw (in degrees). name: \"angle_p_fc\", shape: [1, 1]",
"sample class for a model. You may choose to use",
"= next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape =",
"for running predictions on the input image. ''' self.image =",
"pre_image} # infer = self.net_exec.start_async(request_id=0, inputs=input_dict) # status = infer.wait()",
"self.core = IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device)",
"self.device = device self.extensions = extensions # self.check_model() # try:",
"- initialise the model ''' try: self.model = IENetwork(self.model_structure, self.model_weights)",
"a sample class for a model. You may choose to",
"number of channels H - image height W - image",
"next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape",
"on the input image. ''' self.image = image print('HeadPose predict..')",
"not_supported) if not self.extensions == None: print('***Quick fix.\\n ~CPU Extension",
"raise('Something is wrong.. ~debug load model~') try: self.input_name = next(iter(self.net.inputs))",
"class Model_HeadPose: ''' Class for the Head Pose Estimation Model.",
"# self.input_name = next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape # self.output_name",
"self.input_name = next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape # self.output_name =",
"self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise.. completed.') # except Exception as",
"''' Check - initialise the model ''' try: self.model =",
"self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception as e: raise ValueError('Something is",
"''' try: print('Model is loading...') self.core = IECore() self.net =",
"= self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception as e: raise ValueError('Something",
"If your model requires any Plugins, this is where you",
"choose to use it as-is or make any changes to",
"0 and self.device == 'CPU': print('Unsuported', not_supported) if not self.extensions",
"image def preprocess_output(self, outputs): ''' Output layer names in Inference",
"names in Inference Engine format: name: \"angle_y_fc\", shape: [1, 1]",
"in self.net.layers.keys() if layer not in supported] if len(not_supported) !=",
"size C - number of channels H - image height",
"def preprocess_input(self, image): ''' An input image in [1xCxHxW] format.",
"# try: # self.input_name = next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape",
"self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape #",
"is wrong.. ~debug load model~') try: self.input_name = next(iter(self.net.inputs)) self.input_shape",
"import sys class Model_HeadPose: ''' Class for the Head Pose",
"initialise the model ''' try: self.model = IENetwork(self.model_structure, self.model_weights) except",
"print('Check the extension path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except Exception",
"self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except Exception as e: raise('Something is",
"shape: [1, 1] - Estimated roll (in degrees). ''' object_list",
"import cv2 import sys class Model_HeadPose: ''' Class for the",
"if not self.extensions == None: print('***Quick fix.\\n ~CPU Extension added')",
"Extension added') self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net, self.device) not_supported =",
"[layer for layer in self.net.layers.keys() if layer not in supported]",
"not Initialise the network. Have you enterred the correct model",
"provided just to give you an idea of how to",
"*image.shape) return image def preprocess_output(self, outputs): ''' Output layer names",
"give you an idea of how to structure your model",
"the user. If your model requires any Plugins, this is",
"is loading...') self.core = IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported =",
"and output values..') def load_model(self): ''' This method is for",
"# raise ValueError('Something is wrong with input and output values..')",
"not in supported] if len(not_supported) == 0: print('***Quick fix, Failed.')",
"roll (in degrees). ''' object_list = [] print('PreOutput-headpose..') # print(outputs)",
"completed.') except Exception as e: raise ValueError('Something is wrong with",
"is a sample class for a model. You may choose",
"width ''' image = cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image = image.transpose((2,",
"= self.core.query_network(self.net, self.device) not_supported = [layer for layer in self.net.layers.keys()",
"- number of channels H - image height W -",
"try: self.model = IENetwork(self.model_structure, self.model_weights) except Exception as e: raise",
"is wrong with input and output values..') def load_model(self): '''",
"image. ''' self.image = image print('HeadPose predict..') pre_image = self.preprocess_input(self.image)",
"# results = infer.outputs[self.output_name] # print(results) # print(self.input_name) # outputs",
"specified by the user. If your model requires any Plugins,",
"idea of how to structure your model class. ''' from",
"raise ValueError(\"Could not Initialise the network. Have you enterred the",
"the correct model path?\") def preprocess_input(self, image): ''' An input",
"= self.core.load_network(network=self.net, device_name=self.device) except Exception as e: raise('Something is wrong..",
"Model. ''' def __init__(self, model_name, device='CPU', extensions=None): self.model_weights = model_name+'.bin'",
"''' def __init__(self, model_name, device='CPU', extensions=None): self.model_weights = model_name+'.bin' self.model_structure",
"''' from openvino.inference_engine import IENetwork, IECore import numpy as np",
"IENetwork, IECore import numpy as np import os import cv2",
"not in supported] if len(not_supported) != 0 and self.device ==",
"status == 0: # results = infer.outputs[self.output_name] # print(results) #",
"next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception as e:",
"self.model_weights = model_name+'.bin' self.model_structure = model_name+'.xml' self.device = device self.extensions",
"<filename>src/.ipynb_checkpoints/headpose_model-checkpoint.py<gh_stars>0 ''' This is a sample class for a model.",
"a model. You may choose to use it as-is or",
"Head Pose Estimation Model. ''' def __init__(self, model_name, device='CPU', extensions=None):",
"from openvino.inference_engine import IENetwork, IECore import numpy as np import",
"extension path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except Exception as e:",
"your model class. ''' from openvino.inference_engine import IENetwork, IECore import",
"{input_name: pre_image} # infer = self.net_exec.start_async(request_id=0, inputs=input_dict) # status =",
"self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) # if status == 0: #",
"def check_model(self): ''' Check - initialise the model ''' try:",
"values..') def load_model(self): ''' This method is for loading the",
"in supported] if len(not_supported) == 0: print('***Quick fix, Failed.') else:",
"1] - Estimated yaw (in degrees). name: \"angle_p_fc\", shape: [1,",
"inputs=input_dict) # status = infer.wait() results = self.net_exec.infer(input_dict) outputs =",
"import os import cv2 import sys class Model_HeadPose: ''' Class",
"self.model = IENetwork(self.model_structure, self.model_weights) except Exception as e: raise ValueError(\"Could",
"'CPU': print('Unsuported', not_supported) if not self.extensions == None: print('***Quick fix.\\n",
"device='CPU', extensions=None): self.model_weights = model_name+'.bin' self.model_structure = model_name+'.xml' self.device =",
"preprocess_output(self, outputs): ''' Output layer names in Inference Engine format:",
"model_name, device='CPU', extensions=None): self.model_weights = model_name+'.bin' self.model_structure = model_name+'.xml' self.device",
"user. If your model requires any Plugins, this is where",
"except Exception as e: raise('Something is wrong.. ~debug load model~')",
"pre_image = self.preprocess_input(self.image) input_name = self.input_name input_dict = {input_name: pre_image}",
"e: raise ValueError(\"Could not Initialise the network. Have you enterred",
"image in [1xCxHxW] format. B - batch size C -",
"try: print('Model is loading...') self.core = IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights)",
"raise ValueError('Something is wrong with input and output values..') def",
"Output layer names in Inference Engine format: name: \"angle_y_fc\", shape:",
"model class. ''' from openvino.inference_engine import IENetwork, IECore import numpy",
"1] - Estimated roll (in degrees). ''' object_list = []",
"''' Output layer names in Inference Engine format: name: \"angle_y_fc\",",
"= self.preprocess_output(results) # if status == 0: # results =",
"image = cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image = image.transpose((2, 0, 1))",
"name: \"angle_r_fc\", shape: [1, 1] - Estimated roll (in degrees).",
"wrong with input and output values..') def predict(self, image): '''",
"= self.input_name input_dict = {input_name: pre_image} # infer = self.net_exec.start_async(request_id=0,",
"= image.reshape(1, *image.shape) return image def preprocess_output(self, outputs): ''' Output",
"self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.') except",
"not self.extensions == None: print('***Quick fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions,",
"for layer in self.net.layers.keys() if layer not in supported] if",
"print('Unsuported', not_supported) if not self.extensions == None: print('***Quick fix.\\n ~CPU",
"# self.input_shape = self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs)) # self.output_shape",
"image = image.transpose((2, 0, 1)) image = image.reshape(1, *image.shape) return",
"Exception as e: raise ValueError('Something is wrong with input and",
"input image in [1xCxHxW] format. B - batch size C",
"''' Class for the Head Pose Estimation Model. ''' def",
"in self.net.layers.keys() if layer not in supported] if len(not_supported) ==",
"batch size C - number of channels H - image",
"self.model_structure = model_name+'.xml' self.device = device self.extensions = extensions #",
"\"angle_y_fc\", shape: [1, 1] - Estimated yaw (in degrees). name:",
"may choose to use it as-is or make any changes",
"= self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) # if status == 0:",
"Exception as e: raise ValueError(\"Could not Initialise the network. Have",
"- image height W - image width ''' image =",
"it. This has been provided just to give you an",
"results = self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) # if status ==",
"[1, 1] - Estimated pitch (in degrees). name: \"angle_r_fc\", shape:",
"path?\") def preprocess_input(self, image): ''' An input image in [1xCxHxW]",
"you enterred the correct model path?\") def preprocess_input(self, image): '''",
"yaw (in degrees). name: \"angle_p_fc\", shape: [1, 1] - Estimated",
"# print('Initialise.. completed.') # except Exception as e: # raise",
"print('Model is loading...') self.core = IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported",
"np import os import cv2 import sys class Model_HeadPose: '''",
"self.preprocess_output(results) # if status == 0: # results = infer.outputs[self.output_name]",
"as e: # raise ValueError('Something is wrong with input and",
"input_name = self.input_name input_dict = {input_name: pre_image} # infer =",
"for the Head Pose Estimation Model. ''' def __init__(self, model_name,",
"(in degrees). name: \"angle_r_fc\", shape: [1, 1] - Estimated roll",
"next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs)) #",
"if status == 0: # results = infer.outputs[self.output_name] # print(results)",
"if len(not_supported) == 0: print('***Quick fix, Failed.') else: print('Check the",
"them. ''' try: print('Model is loading...') self.core = IECore() self.net",
"height W - image width ''' image = cv2.resize(image, (self.input_shape[3],",
"= extensions # self.check_model() # try: # self.input_name = next(iter(self.model.inputs))",
"== None: print('***Quick fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions, device) supported",
"as-is or make any changes to it. This has been",
"completed.') # except Exception as e: # raise ValueError('Something is",
"self.check_model() # try: # self.input_name = next(iter(self.model.inputs)) # self.input_shape =",
"as np import os import cv2 import sys class Model_HeadPose:",
"except Exception as e: raise ValueError(\"Could not Initialise the network.",
"layer in self.net.layers.keys() if layer not in supported] if len(not_supported)",
"correct model path?\") def preprocess_input(self, image): ''' An input image",
"''' This method is meant for running predictions on the",
"Exception as e: raise('Something is wrong.. ~debug load model~') try:",
"model to the device specified by the user. If your",
"outputs = self.preprocess_output(results) return outputs def check_model(self): ''' Check -",
"0, 1)) image = image.reshape(1, *image.shape) return image def preprocess_output(self,",
"[1xCxHxW] format. B - batch size C - number of",
"any changes to it. This has been provided just to",
"model_name+'.bin' self.model_structure = model_name+'.xml' self.device = device self.extensions = extensions",
"- Estimated pitch (in degrees). name: \"angle_r_fc\", shape: [1, 1]",
"= infer.outputs[self.output_name] # print(results) # print(self.input_name) # outputs = self.preprocess_output(results)",
"degrees). name: \"angle_r_fc\", shape: [1, 1] - Estimated roll (in",
"the device specified by the user. If your model requires",
"self.model.outputs[self.output_name].shape # print('Initialise.. completed.') # except Exception as e: #",
"if len(not_supported) != 0 and self.device == 'CPU': print('Unsuported', not_supported)",
"= next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise.. completed.') #",
"ValueError(\"Could not Initialise the network. Have you enterred the correct",
"next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise.. completed.') # except",
"channels H - image height W - image width '''",
"Exception as e: # raise ValueError('Something is wrong with input",
"''' try: self.model = IENetwork(self.model_structure, self.model_weights) except Exception as e:",
"self.input_shape[2])) image = image.transpose((2, 0, 1)) image = image.reshape(1, *image.shape)",
"= image.transpose((2, 0, 1)) image = image.reshape(1, *image.shape) return image",
"This is a sample class for a model. You may",
"1)) image = image.reshape(1, *image.shape) return image def preprocess_output(self, outputs):",
"Failed.') else: print('Check the extension path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device)",
"object_list = [] print('PreOutput-headpose..') # print(outputs) object_list.append(outputs['angle_y_fc'].tolist()[0][0]) object_list.append(outputs['angle_p_fc'].tolist()[0][0]) object_list.append(outputs['angle_r_fc'].tolist()[0][0]) return",
"path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except Exception as e: raise('Something",
"self.core.query_network(self.net, self.device) not_supported = [layer for layer in self.net.layers.keys() if",
"changes to it. This has been provided just to give",
"Engine format: name: \"angle_y_fc\", shape: [1, 1] - Estimated yaw",
"= self.model.outputs[self.output_name].shape # print('Initialise.. completed.') # except Exception as e:",
"e: # raise ValueError('Something is wrong with input and output",
"self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device) not_supported = [layer for layer",
"input and output values..') def predict(self, image): ''' This method",
"= model_name+'.xml' self.device = device self.extensions = extensions # self.check_model()",
"\"angle_r_fc\", shape: [1, 1] - Estimated roll (in degrees). '''",
"image): ''' This method is meant for running predictions on",
"= IENetwork(self.model_structure, self.model_weights) except Exception as e: raise ValueError(\"Could not",
"model requires any Plugins, this is where you can load",
"B - batch size C - number of channels H",
"self.input_name input_dict = {input_name: pre_image} # infer = self.net_exec.start_async(request_id=0, inputs=input_dict)",
"predictions on the input image. ''' self.image = image print('HeadPose",
"= image print('HeadPose predict..') pre_image = self.preprocess_input(self.image) input_name = self.input_name",
"return image def preprocess_output(self, outputs): ''' Output layer names in",
"self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net, self.device) not_supported = [layer for",
"Check - initialise the model ''' try: self.model = IENetwork(self.model_structure,",
"C - number of channels H - image height W",
"= self.preprocess_input(self.image) input_name = self.input_name input_dict = {input_name: pre_image} #",
"output values..') def load_model(self): ''' This method is for loading",
"can load them. ''' try: print('Model is loading...') self.core =",
"= [layer for layer in self.net.layers.keys() if layer not in",
"image = image.reshape(1, *image.shape) return image def preprocess_output(self, outputs): '''",
"has been provided just to give you an idea of",
"degrees). name: \"angle_p_fc\", shape: [1, 1] - Estimated pitch (in",
"This has been provided just to give you an idea",
"image): ''' An input image in [1xCxHxW] format. B -",
"try: self.input_name = next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs))",
"ValueError('Something is wrong with input and output values..') def predict(self,",
"self.net.layers.keys() if layer not in supported] if len(not_supported) == 0:",
"the extension path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except Exception as",
"(in degrees). ''' object_list = [] print('PreOutput-headpose..') # print(outputs) object_list.append(outputs['angle_y_fc'].tolist()[0][0])",
"self.extensions == None: print('***Quick fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions, device)",
"# if status == 0: # results = infer.outputs[self.output_name] #",
"== 0: print('***Quick fix, Failed.') else: print('Check the extension path.')",
"os import cv2 import sys class Model_HeadPose: ''' Class for",
"it as-is or make any changes to it. This has",
"the model ''' try: self.model = IENetwork(self.model_structure, self.model_weights) except Exception",
"as e: raise ValueError(\"Could not Initialise the network. Have you",
"= next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception as",
"supported = self.core.query_network(self.net, self.device) not_supported = [layer for layer in",
"numpy as np import os import cv2 import sys class",
"self.output_name = next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception",
"is meant for running predictions on the input image. '''",
"preprocess_input(self, image): ''' An input image in [1xCxHxW] format. B",
"Estimated roll (in degrees). ''' object_list = [] print('PreOutput-headpose..') #",
"# print(results) # print(self.input_name) # outputs = self.preprocess_output(results) return outputs",
"you can load them. ''' try: print('Model is loading...') self.core",
"model. You may choose to use it as-is or make",
"is wrong with input and output values..') def predict(self, image):",
"infer.outputs[self.output_name] # print(results) # print(self.input_name) # outputs = self.preprocess_output(results) return",
"of channels H - image height W - image width",
"image print('HeadPose predict..') pre_image = self.preprocess_input(self.image) input_name = self.input_name input_dict",
"values..') def predict(self, image): ''' This method is meant for",
"self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device) not_supported = [layer",
"enterred the correct model path?\") def preprocess_input(self, image): ''' An",
"class for a model. You may choose to use it",
"''' image = cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image = image.transpose((2, 0,",
"if layer not in supported] if len(not_supported) != 0 and",
"try: # self.input_name = next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape #",
"method is for loading the model to the device specified",
"self.net.layers.keys() if layer not in supported] if len(not_supported) != 0",
"infer.wait() results = self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) # if status",
"extensions # self.check_model() # try: # self.input_name = next(iter(self.model.inputs)) #",
"print(results) # print(self.input_name) # outputs = self.preprocess_output(results) return outputs def",
"wrong.. ~debug load model~') try: self.input_name = next(iter(self.net.inputs)) self.input_shape =",
"self.device == 'CPU': print('Unsuported', not_supported) if not self.extensions == None:",
"!= 0 and self.device == 'CPU': print('Unsuported', not_supported) if not",
"to give you an idea of how to structure your",
"wrong with input and output values..') def load_model(self): ''' This",
"self.model_weights) except Exception as e: raise ValueError(\"Could not Initialise the",
"shape: [1, 1] - Estimated pitch (in degrees). name: \"angle_r_fc\",",
"in supported] if len(not_supported) != 0 and self.device == 'CPU':",
"supported] if len(not_supported) == 0: print('***Quick fix, Failed.') else: print('Check",
"loading the model to the device specified by the user.",
"Plugins, this is where you can load them. ''' try:",
"return outputs def check_model(self): ''' Check - initialise the model",
"This method is for loading the model to the device",
"= self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.')",
"= model_name+'.bin' self.model_structure = model_name+'.xml' self.device = device self.extensions =",
"to the device specified by the user. If your model",
"= cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image = image.transpose((2, 0, 1)) image",
"Inference Engine format: name: \"angle_y_fc\", shape: [1, 1] - Estimated",
"device) supported = self.core.query_network(self.net, self.device) not_supported = [layer for layer",
"model ''' try: self.model = IENetwork(self.model_structure, self.model_weights) except Exception as",
"Estimated pitch (in degrees). name: \"angle_r_fc\", shape: [1, 1] -",
"shape: [1, 1] - Estimated yaw (in degrees). name: \"angle_p_fc\",",
"not_supported = [layer for layer in self.net.layers.keys() if layer not",
"as e: raise ValueError('Something is wrong with input and output",
"def load_model(self): ''' This method is for loading the model",
"of how to structure your model class. ''' from openvino.inference_engine",
"0: print('***Quick fix, Failed.') else: print('Check the extension path.') self.net_exec",
"import numpy as np import os import cv2 import sys",
"# self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise.. completed.') # except Exception",
"''' object_list = [] print('PreOutput-headpose..') # print(outputs) object_list.append(outputs['angle_y_fc'].tolist()[0][0]) object_list.append(outputs['angle_p_fc'].tolist()[0][0]) object_list.append(outputs['angle_r_fc'].tolist()[0][0])",
"Have you enterred the correct model path?\") def preprocess_input(self, image):",
"~debug load model~') try: self.input_name = next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape",
"None: print('***Quick fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions, device) supported =",
"load them. ''' try: print('Model is loading...') self.core = IECore()",
"self.preprocess_input(self.image) input_name = self.input_name input_dict = {input_name: pre_image} # infer",
"import IENetwork, IECore import numpy as np import os import",
"= device self.extensions = extensions # self.check_model() # try: #",
"structure your model class. ''' from openvino.inference_engine import IENetwork, IECore",
"- batch size C - number of channels H -",
"input_dict = {input_name: pre_image} # infer = self.net_exec.start_async(request_id=0, inputs=input_dict) #",
"Pose Estimation Model. ''' def __init__(self, model_name, device='CPU', extensions=None): self.model_weights",
"len(not_supported) != 0 and self.device == 'CPU': print('Unsuported', not_supported) if",
"= next(iter(self.model.inputs)) # self.input_shape = self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs))",
"format. B - batch size C - number of channels",
"how to structure your model class. ''' from openvino.inference_engine import",
"__init__(self, model_name, device='CPU', extensions=None): self.model_weights = model_name+'.bin' self.model_structure = model_name+'.xml'",
"model path?\") def preprocess_input(self, image): ''' An input image in",
"print('Initialise.. completed.') except Exception as e: raise ValueError('Something is wrong",
"- Estimated roll (in degrees). ''' object_list = [] print('PreOutput-headpose..')",
"the input image. ''' self.image = image print('HeadPose predict..') pre_image",
"model_name+'.xml' self.device = device self.extensions = extensions # self.check_model() #",
"An input image in [1xCxHxW] format. B - batch size",
"device self.extensions = extensions # self.check_model() # try: # self.input_name",
"= IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device) not_supported",
"with input and output values..') def predict(self, image): ''' This",
"is where you can load them. ''' try: print('Model is",
"= self.preprocess_output(results) return outputs def check_model(self): ''' Check - initialise",
"layer names in Inference Engine format: name: \"angle_y_fc\", shape: [1,",
"[1, 1] - Estimated yaw (in degrees). name: \"angle_p_fc\", shape:",
"is for loading the model to the device specified by",
"by the user. If your model requires any Plugins, this",
"image width ''' image = cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image =",
"outputs): ''' Output layer names in Inference Engine format: name:",
"status = infer.wait() results = self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) #",
"use it as-is or make any changes to it. This",
"network. Have you enterred the correct model path?\") def preprocess_input(self,",
"outputs def check_model(self): ''' Check - initialise the model '''",
"1] - Estimated pitch (in degrees). name: \"angle_r_fc\", shape: [1,",
"(self.input_shape[3], self.input_shape[2])) image = image.transpose((2, 0, 1)) image = image.reshape(1,",
"pitch (in degrees). name: \"angle_r_fc\", shape: [1, 1] - Estimated",
"self.input_name = next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name = next(iter(self.net.outputs)) self.output_shape",
"the network. Have you enterred the correct model path?\") def",
"\"angle_p_fc\", shape: [1, 1] - Estimated pitch (in degrees). name:",
"self.input_shape = self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs)) # self.output_shape =",
"extensions=None): self.model_weights = model_name+'.bin' self.model_structure = model_name+'.xml' self.device = device",
"to structure your model class. ''' from openvino.inference_engine import IENetwork,",
"loading...') self.core = IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net,",
"input and output values..') def load_model(self): ''' This method is",
"# self.check_model() # try: # self.input_name = next(iter(self.model.inputs)) # self.input_shape",
"image.reshape(1, *image.shape) return image def preprocess_output(self, outputs): ''' Output layer",
"except Exception as e: raise ValueError('Something is wrong with input",
"output values..') def predict(self, image): ''' This method is meant",
"for a model. You may choose to use it as-is",
"= self.model.inputs[self.input_name].shape # self.output_name = next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape",
"running predictions on the input image. ''' self.image = image",
"len(not_supported) == 0: print('***Quick fix, Failed.') else: print('Check the extension",
"Class for the Head Pose Estimation Model. ''' def __init__(self,",
"load_model(self): ''' This method is for loading the model to",
"cv2 import sys class Model_HeadPose: ''' Class for the Head",
"this is where you can load them. ''' try: print('Model",
"image height W - image width ''' image = cv2.resize(image,",
"in [1xCxHxW] format. B - batch size C - number",
"IECore() self.net = self.core.read_network(model=self.model_structure,weights=self.model_weights) supported = self.core.query_network(self.net, self.device) not_supported =",
"= infer.wait() results = self.net_exec.infer(input_dict) outputs = self.preprocess_output(results) # if",
"model~') try: self.input_name = next(iter(self.net.inputs)) self.input_shape = self.net.inputs[self.input_name].shape self.output_name =",
"make any changes to it. This has been provided just",
"device specified by the user. If your model requires any",
"# status = infer.wait() results = self.net_exec.infer(input_dict) outputs = self.preprocess_output(results)",
"IENetwork(self.model_structure, self.model_weights) except Exception as e: raise ValueError(\"Could not Initialise",
"self.device) not_supported = [layer for layer in self.net.layers.keys() if layer",
"print('***Quick fix, Failed.') else: print('Check the extension path.') self.net_exec =",
"print(self.input_name) # outputs = self.preprocess_output(results) return outputs def check_model(self): '''",
"input image. ''' self.image = image print('HeadPose predict..') pre_image =",
"device_name=self.device) except Exception as e: raise('Something is wrong.. ~debug load",
"class. ''' from openvino.inference_engine import IENetwork, IECore import numpy as",
"[1, 1] - Estimated roll (in degrees). ''' object_list =",
"method is meant for running predictions on the input image.",
"= {input_name: pre_image} # infer = self.net_exec.start_async(request_id=0, inputs=input_dict) # status",
"def predict(self, image): ''' This method is meant for running",
"def __init__(self, model_name, device='CPU', extensions=None): self.model_weights = model_name+'.bin' self.model_structure =",
"self.output_name = next(iter(self.model.outputs)) # self.output_shape = self.model.outputs[self.output_name].shape # print('Initialise.. completed.')",
"e: raise ValueError('Something is wrong with input and output values..')",
"supported] if len(not_supported) != 0 and self.device == 'CPU': print('Unsuported',",
"openvino.inference_engine import IENetwork, IECore import numpy as np import os",
"else: print('Check the extension path.') self.net_exec = self.core.load_network(network=self.net, device_name=self.device) except",
"the model to the device specified by the user. If",
"in Inference Engine format: name: \"angle_y_fc\", shape: [1, 1] -",
"You may choose to use it as-is or make any",
"you an idea of how to structure your model class.",
"print('***Quick fix.\\n ~CPU Extension added') self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net,",
"~CPU Extension added') self.core.add_extension(self.extensions, device) supported = self.core.query_network(self.net, self.device) not_supported",
"as e: raise('Something is wrong.. ~debug load model~') try: self.input_name",
"self.preprocess_output(results) return outputs def check_model(self): ''' Check - initialise the",
"to it. This has been provided just to give you",
"# outputs = self.preprocess_output(results) return outputs def check_model(self): ''' Check",
"layer not in supported] if len(not_supported) != 0 and self.device",
"self.output_shape = self.net.outputs[self.output_name].shape print('Initialise.. completed.') except Exception as e: raise",
"infer = self.net_exec.start_async(request_id=0, inputs=input_dict) # status = infer.wait() results =",
"Model_HeadPose: ''' Class for the Head Pose Estimation Model. '''",
"print('Initialise.. completed.') # except Exception as e: # raise ValueError('Something",
"''' self.image = image print('HeadPose predict..') pre_image = self.preprocess_input(self.image) input_name",
"predict..') pre_image = self.preprocess_input(self.image) input_name = self.input_name input_dict = {input_name:",
"e: raise('Something is wrong.. ~debug load model~') try: self.input_name =",
"if layer not in supported] if len(not_supported) == 0: print('***Quick",
"''' This is a sample class for a model. You",
"and self.device == 'CPU': print('Unsuported', not_supported) if not self.extensions ==",
"ValueError('Something is wrong with input and output values..') def load_model(self):",
"- image width ''' image = cv2.resize(image, (self.input_shape[3], self.input_shape[2])) image",
"your model requires any Plugins, this is where you can",
"''' An input image in [1xCxHxW] format. B - batch"
] |
[
"= \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\" DATE_TIME_FORMAT_FRACTIONAL =",
"NAMES_SAML2_ASSERTION = \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT",
"= \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT =",
"= \"urn:oasis:names:tc:SAML:2.0:protocol\" NAMES_SAML2_ASSERTION = \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST =",
"NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\" DATE_TIME_FORMAT_FRACTIONAL",
"\"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\"",
"\"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\" DATE_TIME_FORMAT = \"%Y-%m-%dT%H:%M:%SZ\" DATE_TIME_FORMAT_FRACTIONAL = \"%Y-%m-%dT%H:%M:%S.%fZ\"",
"NAMES_SAML2_PROTOCOL = \"urn:oasis:names:tc:SAML:2.0:protocol\" NAMES_SAML2_ASSERTION = \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST",
"\"urn:oasis:names:tc:SAML:2.0:protocol\" NAMES_SAML2_ASSERTION = \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\" BINDINGS_HTTP_POST = \"urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST\"",
"<gh_stars>1-10 NAMES_SAML2_PROTOCOL = \"urn:oasis:names:tc:SAML:2.0:protocol\" NAMES_SAML2_ASSERTION = \"urn:oasis:names:tc:SAML:2.0:assertion\" NAMEID_FORMAT_UNSPECIFIED = \"urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified\""
] |
[
"def check(n): if semprime(n) == True: return True else: return",
"else: return True def semprime(n): ch = 0 if square(n)==False:",
"for _ in range(int(input())): n=int(input()) flag=0 for i in range(2,n//2+1):",
"if(n > 1): ch += 1 return ch == 2",
"else: return False for _ in range(int(input())): n=int(input()) flag=0 for",
"n=int(input()) flag=0 for i in range(2,n//2+1): if check(i)==True and check(n-i)==True:",
"== 2 def check(n): if semprime(n) == True: return True",
"semprime(n): ch = 0 if square(n)==False: return False for i",
"square(n): tmp=round(math.sqrt(n)) if tmp*tmp==n: return False else: return True def",
"tmp*tmp==n: return False else: return True def semprime(n): ch =",
"int(math.sqrt(n)) + 1): while n%i==0: n//=i ch+=1 if ch >=",
"False for _ in range(int(input())): n=int(input()) flag=0 for i in",
"ch == 2 def check(n): if semprime(n) == True: return",
"if ch >= 2: break if(n > 1): ch +=",
"range(2, int(math.sqrt(n)) + 1): while n%i==0: n//=i ch+=1 if ch",
"range(int(input())): n=int(input()) flag=0 for i in range(2,n//2+1): if check(i)==True and",
"1 return ch == 2 def check(n): if semprime(n) ==",
"n%i==0: n//=i ch+=1 if ch >= 2: break if(n >",
"break if(n > 1): ch += 1 return ch ==",
"if square(n)==False: return False for i in range(2, int(math.sqrt(n)) +",
"i in range(2, int(math.sqrt(n)) + 1): while n%i==0: n//=i ch+=1",
">= 2: break if(n > 1): ch += 1 return",
"return ch == 2 def check(n): if semprime(n) == True:",
"return False for _ in range(int(input())): n=int(input()) flag=0 for i",
"1): while n%i==0: n//=i ch+=1 if ch >= 2: break",
"ch >= 2: break if(n > 1): ch += 1",
"check(n): if semprime(n) == True: return True else: return False",
"True else: return False for _ in range(int(input())): n=int(input()) flag=0",
"in range(int(input())): n=int(input()) flag=0 for i in range(2,n//2+1): if check(i)==True",
"ch = 0 if square(n)==False: return False for i in",
"def square(n): tmp=round(math.sqrt(n)) if tmp*tmp==n: return False else: return True",
"return False for i in range(2, int(math.sqrt(n)) + 1): while",
"if tmp*tmp==n: return False else: return True def semprime(n): ch",
"import math def square(n): tmp=round(math.sqrt(n)) if tmp*tmp==n: return False else:",
"= 0 if square(n)==False: return False for i in range(2,",
"in range(2, int(math.sqrt(n)) + 1): while n%i==0: n//=i ch+=1 if",
"return True else: return False for _ in range(int(input())): n=int(input())",
"2 def check(n): if semprime(n) == True: return True else:",
"range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1 break if",
"False else: return True def semprime(n): ch = 0 if",
"True: return True else: return False for _ in range(int(input())):",
"tmp=round(math.sqrt(n)) if tmp*tmp==n: return False else: return True def semprime(n):",
"if semprime(n) == True: return True else: return False for",
"_ in range(int(input())): n=int(input()) flag=0 for i in range(2,n//2+1): if",
"def semprime(n): ch = 0 if square(n)==False: return False for",
"check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1 break if flag==0: #print(i,n-i,square(i),square(n-i),\"No\")",
"in range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1 break",
"+= 1 return ch == 2 def check(n): if semprime(n)",
"return False else: return True def semprime(n): ch = 0",
"return True def semprime(n): ch = 0 if square(n)==False: return",
"square(n)==False: return False for i in range(2, int(math.sqrt(n)) + 1):",
"ch+=1 if ch >= 2: break if(n > 1): ch",
"for i in range(2, int(math.sqrt(n)) + 1): while n%i==0: n//=i",
"1): ch += 1 return ch == 2 def check(n):",
"ch += 1 return ch == 2 def check(n): if",
"True def semprime(n): ch = 0 if square(n)==False: return False",
"flag=0 for i in range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\")",
"for i in range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\")",
"and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1 break if flag==0: #print(i,n-i,square(i),square(n-i),\"No\") print(\"NO\")",
"semprime(n) == True: return True else: return False for _",
"i in range(2,n//2+1): if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1",
"if check(i)==True and check(n-i)==True: #print(i,n-i,square(i),square(n-i),\"Yes\") print(\"YES\") flag=1 break if flag==0:",
"math def square(n): tmp=round(math.sqrt(n)) if tmp*tmp==n: return False else: return",
"False for i in range(2, int(math.sqrt(n)) + 1): while n%i==0:",
"0 if square(n)==False: return False for i in range(2, int(math.sqrt(n))",
"<reponame>PK-100/Competitive_Programming import math def square(n): tmp=round(math.sqrt(n)) if tmp*tmp==n: return False",
"> 1): ch += 1 return ch == 2 def",
"== True: return True else: return False for _ in",
"while n%i==0: n//=i ch+=1 if ch >= 2: break if(n",
"2: break if(n > 1): ch += 1 return ch",
"n//=i ch+=1 if ch >= 2: break if(n > 1):",
"+ 1): while n%i==0: n//=i ch+=1 if ch >= 2:"
] |
[
"packages=find_packages(), version='0.1.0', description='This repository hosts some work-in-progress experiments applying deep",
"some work-in-progress experiments applying deep learning to predict age using",
"description='This repository hosts some work-in-progress experiments applying deep learning to",
"experiments applying deep learning to predict age using tractometry data.',",
"find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='This repository hosts some",
"setup( name='src', packages=find_packages(), version='0.1.0', description='This repository hosts some work-in-progress experiments",
"setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='This repository",
"repository hosts some work-in-progress experiments applying deep learning to predict",
"applying deep learning to predict age using tractometry data.', author='<NAME>',",
"hosts some work-in-progress experiments applying deep learning to predict age",
"import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='This repository hosts",
"<reponame>arokem/afq-deep-learning<filename>setup.py from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0',",
"name='src', packages=find_packages(), version='0.1.0', description='This repository hosts some work-in-progress experiments applying",
"deep learning to predict age using tractometry data.', author='<NAME>', license='BSD-3',",
"learning to predict age using tractometry data.', author='<NAME>', license='BSD-3', )",
"from setuptools import find_packages, setup setup( name='src', packages=find_packages(), version='0.1.0', description='This",
"version='0.1.0', description='This repository hosts some work-in-progress experiments applying deep learning",
"setup setup( name='src', packages=find_packages(), version='0.1.0', description='This repository hosts some work-in-progress",
"work-in-progress experiments applying deep learning to predict age using tractometry"
] |
[
"volume_size = args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image",
"= get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image)",
"return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url =",
"\"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE = \"split\"",
"stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_path = f.name for",
"\" \"it has not been implemented yet.\") def import_image_if_needed(base_image): if",
"args = parser.parse_args() distro = args.distro container_name = args.cname base_image",
"container_name, default_image, container_name, container_name), shell=True) except Exception as e: exit_with_error(str(e))",
"and split. We support both. For unified format, the manifest",
"uuid from libs import colorprint from libs.cli import run_command SCRIPT_DIR",
"import {} {} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path)",
"been implemented yet.\") def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise Exception(\"{}",
"<filename>make_base_container.py #!/usr/bin/env python3 import argparse import os import random import",
"imported\".format(base_image)) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str,",
"def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r =",
"\"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = [] for url in [metadata_tarball_url, rootfs_tarball_url]:",
"look like this: { \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\",",
"'for RHEL distro, \\'ubuntu:16.04\\' otherwise') args = parser.parse_args() distro =",
"manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc image",
"default_image try: # make a container profile that maps 8",
"requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for chunk",
"manifest[\"tarball_type\"] not in TARBALL_TYPES: raise Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"]))",
"alias): metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest) # There might be",
"raise Exception(\"Tarball type '{}' is valid, but a method to",
"{} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL,",
"import colorprint from libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) #",
"For unified format, the manifest will look like this: {",
"not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not an image hosted by",
"image \" \"{}\".format(base_image)) run_command(\"lxc launch {} {} -p {}-profile ||",
"e: raise Exception(\"Could not download container image manifest from '{}'.\"",
"new chunks f.write(chunk) except Exception as e: print(\"Could not download",
"rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} |",
"with tempfile.NamedTemporaryFile(delete=False) as f: file_path = f.name for chunk in",
"delete {}\".format(alias)) except Exception: pass def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL,",
"tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r = requests.get(tarball_url, stream=True) r.raise_for_status()",
"\"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r = requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False)",
"maps 8 block devices to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128)))",
"try: r = requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f:",
"import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest) # There might",
"= f.name for chunk in r.iter_content(chunk_size=1024): if chunk: # filter",
"cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc",
"chunks f.write(chunk) except Exception as e: print(\"Could not download file",
"container_name, container_name, default_image, container_name, container_name), shell=True) except Exception as e:",
"is None: base_image = default_image try: # make a container",
"import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume",
"on host # ...later we'll figure out how to make",
"is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not an image hosted by \"",
"\"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"] not in TARBALL_TYPES:",
"except Exception: return False return True def delete_image_with_alias(alias): try: run_command(\"lxc",
"has not been implemented yet.\") def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image):",
"an older image with the same alias delete_image_with_alias(alias) run_command(\"lxc image",
"True def delete_image_with_alias(alias): try: run_command(\"lxc image delete {}\".format(alias)) except Exception:",
"base_image is None: base_image = default_image try: # make a",
"download file from '{}': {}\".format(tarball_url, e)) return file_path def import_unified_image(manifest,",
"type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume",
"VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create {}-profile\".format(container_name))",
"\\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE =",
"r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks f.write(chunk)",
"type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\' '",
"\"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername',",
"raise Exception(\"{} is not an image hosted by \" \"SwiftStack\".format(base_image))",
"= download_unified_image_file(manifest) # There might be an older image with",
"if base_image is None: base_image = default_image try: # make",
"help='Volume size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image.",
"\"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format, the",
"lvm volume group on host # ...later we'll figure out",
"image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc",
"SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text)",
"return False return True def delete_image_with_alias(alias): try: run_command(\"lxc image delete",
"print(\"Could not download file from '{}': {}\".format(tarball_url, e)) return file_path",
"run_command(\"cat /tmp/{} | lxc profile edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR,",
"def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not an",
"{}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc profile edit {}-profile\".format( rand_file_name, container_name),",
"\\'ubuntu:16.04\\' otherwise') args = parser.parse_args() distro = args.distro container_name =",
"this: { \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\"",
"'{}' is already imported\".format(base_image)) if __name__ == \"__main__\": parser =",
"r = requests.get(manifest_obj_url) r.raise_for_status() return r.json() except Exception as e:",
"{}\".format(tarball_url, e)) return file_path def import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest)",
"by \" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if",
"filter out keep-alive new chunks f.write(chunk) except Exception as e:",
"same alias delete_image_with_alias(alias) run_command(\"lxc image import {} --alias {}\".format(tarball_path, alias))",
"parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base",
"{} {} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def",
"False return True def delete_image_with_alias(alias): try: run_command(\"lxc image delete {}\".format(alias))",
"def import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest) # There might be",
"\"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE,",
"--alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"])",
"tarball type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias)",
"\"{}\".format(base_image)) run_command(\"lxc launch {} {} -p {}-profile || \" \"lxc",
"well-known lvm volume group on host # ...later we'll figure",
"image with the same alias delete_image_with_alias(alias) run_command(\"lxc image import {}",
"tarball_path = download_unified_image_file(manifest) # There might be an older image",
"str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {} {} > \" \"/tmp/{}\".format(container_name, VG_NAME,",
"args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro",
"def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if distro.lower() == \"rhel\":",
"except Exception as e: raise Exception(\"Could not download container image",
"return tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest)",
"{} {} -p {}-profile\".format(base_image, container_name, container_name, default_image, container_name, container_name), shell=True)",
"-p {}-profile || \" \"lxc launch {} {} -p {}-profile\".format(base_image,",
"VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\"",
"\"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"] not in TARBALL_TYPES: raise Exception(\"Invalid",
"\"rhel\": return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX)",
"profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc profile edit {}-profile\".format(",
"f: file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024): if chunk: # filter",
"from libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known",
"type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif",
"rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch the new container print(\"Trying",
"import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest) # There might be an",
"file from '{}': {}\".format(url, e)) return tuple(file_paths) def import_split_image(manifest, alias):",
"format, the manifest will look like this: { \"tarball_type\": \"split\",",
"Exception(\"Tarball type '{}' is valid, but a method to import",
"count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL",
"new container print(\"Trying to launch container from base image \"",
"[metadata_tarball_url, rootfs_tarball_url]: try: r = requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False)",
"Exception(\"{} is not an image hosted by \" \"SwiftStack\".format(base_image)) swift_container_name",
"{} -p {}-profile\".format(base_image, container_name, container_name, default_image, container_name, container_name), shell=True) except",
"rootfs_tarball_path = \\ download_split_image_files(manifest) # There might be an older",
"file_paths = [] for url in [metadata_tarball_url, rootfs_tarball_url]: try: r",
"as e: print(\"Could not download file from '{}': {}\".format(url, e))",
"edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch the new",
"= \"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def",
"from libs import colorprint from libs.cli import run_command SCRIPT_DIR =",
"image delete {}\".format(alias)) except Exception: pass def download_unified_image_file(manifest): tarball_url =",
"download_split_image_files(manifest) # There might be an older image with the",
"There are 2 possible image formats: unified and split. We",
"\"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"]",
"manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url) r.raise_for_status()",
"will look like this: { \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\":",
"an image hosted by \" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest",
"alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception(\"Tarball",
"try: r = requests.get(manifest_obj_url) r.raise_for_status() return r.json() except Exception as",
"= requests.get(manifest_obj_url) r.raise_for_status() return r.json() except Exception as e: raise",
"sys.exit(1) def get_default_image(distro): if distro.lower() == \"rhel\": return \"images:centos/7/amd64\" else:",
"raise Exception(\"Could not download container image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url,",
"container image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try:",
"parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int,",
"r.json() except Exception as e: raise Exception(\"Could not download container",
"# assume well-known lvm volume group on host # ...later",
"= requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for",
"__name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro')",
"a container profile that maps 8 block devices to the",
"image import {} {} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path)",
"print(\"Trying to launch container from base image \" \"{}\".format(base_image)) run_command(\"lxc",
"f: file_path = f.name for chunk in r.iter_content(chunk_size=1024): if chunk:",
"= requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_path =",
"= default_image try: # make a container profile that maps",
"import requests import sys import tempfile import uuid from libs",
"size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults:",
"= \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1)",
"{}\".format(alias)) except Exception: pass def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"])",
"os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL,",
"requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_path = f.name",
"e)) return tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path = \\",
"r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_path = f.name for chunk",
"if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container",
"os import random import requests import sys import tempfile import",
"base image \" \"{}\".format(base_image)) run_command(\"lxc launch {} {} -p {}-profile",
"if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image",
"help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\' ' 'for",
"[UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if distro.lower()",
"\"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"] not in",
"we'll figure out how to make this dynamic VG_NAME =",
"TARBALL_TYPES: raise Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] ==",
"implemented yet.\") def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is",
"exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if distro.lower() == \"rhel\": return",
"like this: { \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\":",
"formats: unified and split. We support both. For unified format,",
"chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new",
"out how to make this dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX",
"= [] for url in [metadata_tarball_url, rootfs_tarball_url]: try: r =",
"with the same alias delete_image_with_alias(alias) run_command(\"lxc image import {} {}",
"== \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname',",
"print(\"Image '{}' is already imported\".format(base_image)) if __name__ == \"__main__\": parser",
"volume group on host # ...later we'll figure out how",
"{ \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" }",
"= args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else: default_image",
"parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize',",
"run_command(\"lxc image info {} >/dev/null 2>&1\".format(fingerprint), shell=True) except Exception: return",
"from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc image info",
"\" \"lxc launch {} {} -p {}-profile\".format(base_image, container_name, container_name, default_image,",
"get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image) else:",
"same alias delete_image_with_alias(alias) run_command(\"lxc image import {} {} --alias {}\".format(",
"== \"rhel\": return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return",
"\"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"] not",
"requests.get(manifest_obj_url) r.raise_for_status() return r.json() except Exception as e: raise Exception(\"Could",
"make a container profile that maps 8 block devices to",
"= args.baseimage volume_size = args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro):",
"We support both. For unified format, the manifest will look",
"\"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if manifest[\"tarball_type\"] not in TARBALL_TYPES: raise",
"hosted by \" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name)",
"unified and split. We support both. For unified format, the",
"metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest) # There might be an",
"argparse import os import random import requests import sys import",
"manifest will look like this: { \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\",",
"the new container print(\"Trying to launch container from base image",
"image formats: unified and split. We support both. For unified",
"'{}': {}\".format(url, e)) return tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path",
"with the same alias delete_image_with_alias(alias) run_command(\"lxc image import {} --alias",
"'{}' is valid, but a method to import \" \"it",
"{} {} {} {} > \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count,",
"colorprint from libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume",
"lxc profile edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch",
"tempfile import uuid from libs import colorprint from libs.cli import",
"r = requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_path",
"print(\"Could not download file from '{}': {}\".format(url, e)) return tuple(file_paths)",
"is not an image hosted by \" \"SwiftStack\".format(base_image)) swift_container_name =",
"if not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not an image hosted",
"base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image))",
"{} {} -p {}-profile || \" \"lxc launch {} {}",
"requests import sys import tempfile import uuid from libs import",
"e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc image info {} >/dev/null 2>&1\".format(fingerprint),",
"= \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = []",
"in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive new chunks",
"rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {} {} > \"",
"Exception as e: print(\"Could not download file from '{}': {}\".format(tarball_url,",
"manifest[\"rootfs-object\"]) file_paths = [] for url in [metadata_tarball_url, rootfs_tarball_url]: try:",
"= get_default_image(distro) if base_image is None: base_image = default_image try:",
"else: print(\"Image '{}' is already imported\".format(base_image)) if __name__ == \"__main__\":",
"= base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image",
"return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def",
"base_image) else: print(\"Image '{}' is already imported\".format(base_image)) if __name__ ==",
"= \\ download_split_image_files(manifest) # There might be an older image",
"import_split_image(manifest, alias) else: raise Exception(\"Tarball type '{}' is valid, but",
"raise Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE:",
"'{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc image info {}",
"= \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = [] for url in [metadata_tarball_url,",
"look like this: { \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\"",
"manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest,",
"is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME)",
"= os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume group on host",
"for url in [metadata_tarball_url, rootfs_tarball_url]: try: r = requests.get(url, stream=True)",
"\"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } '''",
"unified format, the manifest will look like this: { \"tarball_type\":",
"\"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL,",
"help='Container ' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume count')",
"# launch the new container print(\"Trying to launch container from",
"shell=True) run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc profile",
"in TARBALL_TYPES: raise Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"]",
"2>&1\".format(fingerprint), shell=True) except Exception: return False return True def delete_image_with_alias(alias):",
"alias delete_image_with_alias(alias) run_command(\"lxc image import {} {} --alias {}\".format( metadata_tarball_path,",
"download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r = requests.get(tarball_url, stream=True)",
"# There might be an older image with the same",
"the manifest will look like this: { \"tarball_type\": \"split\", \"fingerprint\":",
"older image with the same alias delete_image_with_alias(alias) run_command(\"lxc image import",
"/tmp/{} | lxc profile edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True)",
"\"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint): try: run_command(\"lxc image info {} >/dev/null",
"Exception(\"Could not download container image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e))",
"metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume",
"\"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format, the manifest will",
"run_command(\"./make_lxc_profile.py {} {} {} {} > \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size,",
"out keep-alive new chunks f.write(chunk) except Exception as e: print(\"Could",
"to launch container from base image \" \"{}\".format(base_image)) run_command(\"lxc launch",
"= argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container '",
"alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias): ''' There are 2",
"python3 import argparse import os import random import requests import",
"yet.\") def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not",
"= args.cname base_image = args.baseimage volume_size = args.volsize volume_count =",
"if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else: default_image = get_default_image(distro)",
"if chunk: # filter out keep-alive new chunks f.write(chunk) except",
"\"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create",
"split format, the manifest will look like this: { \"tarball_type\":",
"== UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias)",
"manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = [] for url",
"distro else: default_image = get_default_image(distro) if base_image is None: base_image",
"import random import requests import sys import tempfile import uuid",
"run_command(\"lxc image delete {}\".format(alias)) except Exception: pass def download_unified_image_file(manifest): tarball_url",
"args.baseimage volume_size = args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro)",
"Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest,",
"method to import \" \"it has not been implemented yet.\")",
"figure out how to make this dynamic VG_NAME = \"swift-runway-vg01\"",
"container_name = args.cname base_image = args.baseimage volume_size = args.volsize volume_count",
"try: run_command(\"lxc image delete {}\".format(alias)) except Exception: pass def download_unified_image_file(manifest):",
"return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try:",
"> \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc",
"the manifest will look like this: { \"tarball_type\": \"unified\", \"fingerprint\":",
"download container image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def is_image_already_imported(fingerprint):",
"{} >/dev/null 2>&1\".format(fingerprint), shell=True) except Exception: return False return True",
"e)) return file_path def import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest) #",
"type '{}' is valid, but a method to import \"",
"volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{}",
"import_image(manifest, base_image) else: print(\"Image '{}' is already imported\".format(base_image)) if __name__",
"from '{}': {}\".format(tarball_url, e)) return file_path def import_unified_image(manifest, alias): tarball_path",
"UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else:",
"distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount',",
"group on host # ...later we'll figure out how to",
"file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out",
"from '{}': {}\".format(url, e)) return tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path,",
"import os import random import requests import sys import tempfile",
"except Exception as e: print(\"Could not download file from '{}':",
"container_name), cwd=SCRIPT_DIR, shell=True) # launch the new container print(\"Trying to",
"container profile that maps 8 block devices to the guest",
"base_image = args.baseimage volume_size = args.volsize volume_count = args.volcount if",
"args.distro container_name = args.cname base_image = args.baseimage volume_size = args.volsize",
"might be an older image with the same alias delete_image_with_alias(alias)",
"= \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES =",
"run_command(\"lxc launch {} {} -p {}-profile || \" \"lxc launch",
"that maps 8 block devices to the guest rand_file_name =",
"{} > \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True)",
"= \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r = requests.get(tarball_url, stream=True) r.raise_for_status() with",
"r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024):",
"tempfile.NamedTemporaryFile(delete=False) as f: file_path = f.name for chunk in r.iter_content(chunk_size=1024):",
"\"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format,",
"''' There are 2 possible image formats: unified and split.",
"file_path def import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest) # There might",
"libs import colorprint from libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__))",
"container from base image \" \"{}\".format(base_image)) run_command(\"lxc launch {} {}",
"not in TARBALL_TYPES: raise Exception(\"Invalid tarball type: {}\".format( manifest[\"tarball_type\"])) elif",
"try: # make a container profile that maps 8 block",
"rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias): ''' There are",
"default_image = get_default_image(distro) if base_image is None: base_image = default_image",
"alias): ''' There are 2 possible image formats: unified and",
"not download container image manifest from '{}'.\" \"\\n{}\".format(manifest_obj_url, e)) def",
"\"lxc launch {} {} -p {}-profile\".format(base_image, container_name, container_name, default_image, container_name,",
"' 'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage',",
"Exception as e: raise Exception(\"Could not download container image manifest",
"pass def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r =",
"rootfs_tarball_url]: try: r = requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as",
"TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro):",
"possible image formats: unified and split. We support both. For",
"\\ download_split_image_files(manifest) # There might be an older image with",
"create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc profile edit {}-profile\".format( rand_file_name,",
"try: r = requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f:",
"= args.distro container_name = args.cname base_image = args.baseimage volume_size =",
"def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r = requests.get(tarball_url,",
"shell=True) # launch the new container print(\"Trying to launch container",
"f.name for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out",
"\"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]):",
"\"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format, the manifest",
"import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise Exception(\"{} is not an image",
"\"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = [] for",
"-p {}-profile\".format(base_image, container_name, container_name, default_image, container_name, container_name), shell=True) except Exception",
"SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume group on",
"host # ...later we'll figure out how to make this",
"run_command(\"lxc image import {} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest):",
"import_image_if_needed(distro) default_image = distro else: default_image = get_default_image(distro) if base_image",
"RHEL distro, \\'ubuntu:16.04\\' otherwise') args = parser.parse_args() distro = args.distro",
"devices to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {}",
"container print(\"Trying to launch container from base image \" \"{}\".format(base_image))",
"# filter out keep-alive new chunks f.write(chunk) except Exception as",
"} ''' if manifest[\"tarball_type\"] not in TARBALL_TYPES: raise Exception(\"Invalid tarball",
"else: raise Exception(\"Tarball type '{}' is valid, but a method",
"\"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name):",
"launch container from base image \" \"{}\".format(base_image)) run_command(\"lxc launch {}",
"random import requests import sys import tempfile import uuid from",
"= distro else: default_image = get_default_image(distro) if base_image is None:",
"else: default_image = get_default_image(distro) if base_image is None: base_image =",
"= args.volsize volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image =",
"cwd=SCRIPT_DIR, shell=True) # launch the new container print(\"Trying to launch",
"{}\".format(url, e)) return tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path =",
"manifest will look like this: { \"tarball_type\": \"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\",",
"def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest) # There",
"\"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format, the manifest will look like",
"8 block devices to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py",
"def delete_image_with_alias(alias): try: run_command(\"lxc image delete {}\".format(alias)) except Exception: pass",
"IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES",
"''' if manifest[\"tarball_type\"] not in TARBALL_TYPES: raise Exception(\"Invalid tarball type:",
"= \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE",
"argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name')",
"help='Base image. Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL distro, \\'ubuntu:16.04\\' otherwise')",
"def is_image_already_imported(fingerprint): try: run_command(\"lxc image info {} >/dev/null 2>&1\".format(fingerprint), shell=True)",
"Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL distro, \\'ubuntu:16.04\\' otherwise') args =",
"to import \" \"it has not been implemented yet.\") def",
"the same alias delete_image_with_alias(alias) run_command(\"lxc image import {} {} --alias",
"file from '{}': {}\".format(tarball_url, e)) return file_path def import_unified_image(manifest, alias):",
"import uuid from libs import colorprint from libs.cli import run_command",
"will look like this: { \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\":",
"url in [metadata_tarball_url, rootfs_tarball_url]: try: r = requests.get(url, stream=True) r.raise_for_status()",
"not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image '{}'",
"tuple(file_paths) def import_split_image(manifest, alias): metadata_tarball_path, rootfs_tarball_path = \\ download_split_image_files(manifest) #",
"image info {} >/dev/null 2>&1\".format(fingerprint), shell=True) except Exception: return False",
"to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {}",
"...later we'll figure out how to make this dynamic VG_NAME",
"alias) else: raise Exception(\"Tarball type '{}' is valid, but a",
"--alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias):",
"how to make this dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX =",
"def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"])",
"= \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE",
"parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL distro,",
"like this: { \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" }",
"\\'images:centos/7/amd64\\' ' 'for RHEL distro, \\'ubuntu:16.04\\' otherwise') args = parser.parse_args()",
"the same alias delete_image_with_alias(alias) run_command(\"lxc image import {} --alias {}\".format(tarball_path,",
"as f: file_path = f.name for chunk in r.iter_content(chunk_size=1024): if",
"\"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text):",
"IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url) r.raise_for_status() return r.json() except Exception",
">/dev/null 2>&1\".format(fingerprint), shell=True) except Exception: return False return True def",
"' 'for RHEL distro, \\'ubuntu:16.04\\' otherwise') args = parser.parse_args() distro",
"{}-profile\".format(base_image, container_name, container_name, default_image, container_name, container_name), shell=True) except Exception as",
"already imported\".format(base_image)) if __name__ == \"__main__\": parser = argparse.ArgumentParser() parser.add_argument('distro',",
"otherwise') args = parser.parse_args() distro = args.distro container_name = args.cname",
"Exception: pass def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try: r",
"manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] ==",
"default_image = distro else: default_image = get_default_image(distro) if base_image is",
"\"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url) r.raise_for_status() return r.json()",
"both. For unified format, the manifest will look like this:",
"distro, \\'ubuntu:16.04\\' otherwise') args = parser.parse_args() distro = args.distro container_name",
"{ \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split",
"if manifest[\"tarball_type\"] not in TARBALL_TYPES: raise Exception(\"Invalid tarball type: {}\".format(",
"def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name,",
"image '{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image '{}' is already imported\".format(base_image))",
"as f: file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024): if chunk: #",
"delete_image_with_alias(alias) run_command(\"lxc image import {} {} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path,",
"launch {} {} -p {}-profile\".format(base_image, container_name, container_name, default_image, container_name, container_name),",
"profile edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch the",
"elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE:",
"def get_default_image(distro): if distro.lower() == \"rhel\": return \"images:centos/7/amd64\" else: return",
"not download file from '{}': {}\".format(url, e)) return tuple(file_paths) def",
"from base image \" \"{}\".format(base_image)) run_command(\"lxc launch {} {} -p",
"delete_image_with_alias(alias): try: run_command(\"lxc image delete {}\".format(alias)) except Exception: pass def",
"not been implemented yet.\") def import_image_if_needed(base_image): if not is_swiftstack_hosted_image(base_image): raise",
"libs.cli import run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm",
"else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image): return base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url",
"def import_image(manifest, alias): ''' There are 2 possible image formats:",
"{}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) # launch the new container",
"as e: raise Exception(\"Could not download container image manifest from",
"the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {} {}",
"Exception as e: print(\"Could not download file from '{}': {}\".format(url,",
"volume_count = args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else:",
"download_unified_image_file(manifest) # There might be an older image with the",
"is_image_already_imported(fingerprint): try: run_command(\"lxc image info {} >/dev/null 2>&1\".format(fingerprint), shell=True) except",
"info {} >/dev/null 2>&1\".format(fingerprint), shell=True) except Exception: return False return",
"\"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For split format, the manifest will look",
"} For split format, the manifest will look like this:",
"{}\".format( manifest[\"tarball_type\"])) elif manifest[\"tarball_type\"] == UNIFIED_TARBALL_TYPE: import_unified_image(manifest, alias) elif manifest[\"tarball_type\"]",
"#!/usr/bin/env python3 import argparse import os import random import requests",
"valid, but a method to import \" \"it has not",
"return r.json() except Exception as e: raise Exception(\"Could not download",
"import \" \"it has not been implemented yet.\") def import_image_if_needed(base_image):",
"r.raise_for_status() return r.json() except Exception as e: raise Exception(\"Could not",
"to make this dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\"",
"dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\",
"block devices to the guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {}",
"manifest = get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest,",
"launch the new container print(\"Trying to launch container from base",
"= parser.parse_args() distro = args.distro container_name = args.cname base_image =",
"{}-profile || \" \"lxc launch {} {} -p {}-profile\".format(base_image, container_name,",
"image. Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL distro, \\'ubuntu:16.04\\' otherwise') args",
"args.cname base_image = args.baseimage volume_size = args.volsize volume_count = args.volcount",
"are 2 possible image formats: unified and split. We support",
"# ...later we'll figure out how to make this dynamic",
"import argparse import os import random import requests import sys",
"return True def delete_image_with_alias(alias): try: run_command(\"lxc image delete {}\".format(alias)) except",
"rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths = [] for url in",
"keep-alive new chunks f.write(chunk) except Exception as e: print(\"Could not",
"import_image(manifest, alias): ''' There are 2 possible image formats: unified",
"= str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {} {} > \" \"/tmp/{}\".format(container_name,",
"SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE = \"unified\"",
"e: print(\"Could not download file from '{}': {}\".format(tarball_url, e)) return",
"parser = argparse.ArgumentParser() parser.add_argument('distro', type=str, help='Container distro') parser.add_argument('cname', metavar='containername', help='Container",
"with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024): if",
"is already imported\".format(base_image)) if __name__ == \"__main__\": parser = argparse.ArgumentParser()",
"try: run_command(\"lxc image info {} >/dev/null 2>&1\".format(fingerprint), shell=True) except Exception:",
"alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url =",
"alias): tarball_path = download_unified_image_file(manifest) # There might be an older",
"= \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME",
"make this dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL",
"nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\' ' 'for RHEL distro, \\'ubuntu:16.04\\'",
"base_image.lower().startswith(SWIFTSTACK_IMAGES_PREFIX) def get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r",
"colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if distro.lower() == \"rhel\": return \"images:centos/7/amd64\"",
"import sys import tempfile import uuid from libs import colorprint",
"'{}': {}\".format(tarball_url, e)) return file_path def import_unified_image(manifest, alias): tarball_path =",
"tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for chunk in r.iter_content(chunk_size=1024): if chunk:",
"None: base_image = default_image try: # make a container profile",
"shell=True) except Exception: return False return True def delete_image_with_alias(alias): try:",
"profile that maps 8 block devices to the guest rand_file_name",
"\"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME =",
"= [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if",
"\"split\", \"fingerprint\": \"22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de\", \"metadata-object\": \"centos7.5/meta-22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.tar.xz\", \"rootfs-object\": \"centos7.5/22abbefe0c68943f264a7139c7a699a0b2adfbcf46fc661d2e89b1232301a5de.squashfs\" } ''' if",
"base_image = default_image try: # make a container profile that",
"# make a container profile that maps 8 block devices",
"this: { \"tarball_type\": \"unified\", \"fingerprint\": \"629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018\", \"tarball-object\": \"centos7.5/629d2c18b7bb0b52b80dfe62ae309937123d05b563ef057233e7802c9e18c018.tar.gz\" } For",
"image import {} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url",
"= \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url) r.raise_for_status() return",
"get_default_image(distro): if distro.lower() == \"rhel\": return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\"",
"{} {} {} > \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name),",
"SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception(\"Tarball type '{}' is valid,",
"download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths",
"a method to import \" \"it has not been implemented",
"get_image_manifest(swift_container_name): manifest_obj_url = \"{}/{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url)",
"os.unlink(rootfs_tarball_path) def import_image(manifest, alias): ''' There are 2 possible image",
"{} {} > \" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR,",
"r = requests.get(url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name)",
"stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as f: file_paths.append(f.name) for chunk in",
"metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias): ''' There",
"\"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\" UNIFIED_TARBALL_TYPE =",
"launch {} {} -p {}-profile || \" \"lxc launch {}",
"for chunk in r.iter_content(chunk_size=1024): if chunk: # filter out keep-alive",
"is valid, but a method to import \" \"it has",
"UNIFIED_TARBALL_TYPE = \"unified\" SPLIT_TARBALL_TYPE = \"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE]",
"'{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image '{}' is already imported\".format(base_image)) if",
"parser.parse_args() distro = args.distro container_name = args.cname base_image = args.baseimage",
"For split format, the manifest will look like this: {",
"'name') parser.add_argument('volsize', help='Volume size') parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?',",
"\" \"{}\".format(base_image)) run_command(\"lxc launch {} {} -p {}-profile || \"",
"import {} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url =",
"SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def get_default_image(distro): if distro.lower() ==",
"import_unified_image(manifest, alias) elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise",
"split. We support both. For unified format, the manifest will",
"import tempfile import uuid from libs import colorprint from libs.cli",
"There might be an older image with the same alias",
"get_default_image(distro) if base_image is None: base_image = default_image try: #",
"swift_container_name, IMAGE_MANIFEST_OBJECT_NAME) try: r = requests.get(manifest_obj_url) r.raise_for_status() return r.json() except",
"guest rand_file_name = str(uuid.UUID(int=random.getrandbits(128))) run_command(\"./make_lxc_profile.py {} {} {} {} >",
"run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat /tmp/{} | lxc profile edit",
"alias delete_image_with_alias(alias) run_command(\"lxc image import {} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path)",
"image hosted by \" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest =",
"\"it has not been implemented yet.\") def import_image_if_needed(base_image): if not",
"args.volcount if is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else: default_image =",
"metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"rootfs-object\"]) file_paths =",
"assume well-known lvm volume group on host # ...later we'll",
"os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias): ''' There are 2 possible",
"return file_path def import_unified_image(manifest, alias): tarball_path = download_unified_image_file(manifest) # There",
"SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL = \\ \"https://tellus.swiftstack.com/v1/AUTH_runway/lxd-images\" IMAGE_MANIFEST_OBJECT_NAME = \"manifest.json\"",
"| lxc profile edit {}-profile\".format( rand_file_name, container_name), cwd=SCRIPT_DIR, shell=True) #",
"{}\".format(tarball_path, alias)) os.unlink(tarball_path) def download_split_image_files(manifest): metadata_tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"metadata-object\"]) rootfs_tarball_url",
"elif manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception(\"Tarball type",
"sys import tempfile import uuid from libs import colorprint from",
"distro = args.distro container_name = args.cname base_image = args.baseimage volume_size",
"is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image '{}' is",
"volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile create {}-profile\".format(container_name)) run_command(\"cat",
"download file from '{}': {}\".format(url, e)) return tuple(file_paths) def import_split_image(manifest,",
"f.write(chunk) except Exception as e: print(\"Could not download file from",
"file_path = f.name for chunk in r.iter_content(chunk_size=1024): if chunk: #",
"this dynamic VG_NAME = \"swift-runway-vg01\" SWIFTSTACK_IMAGES_PREFIX = \"ss-\" SWIFTSTACK_IMAGES_BASE_URL =",
"parser.add_argument('volcount', type=int, help='Volume count') parser.add_argument('baseimage', nargs='?', help='Base image. Defaults: \\'images:centos/7/amd64\\'",
"as e: print(\"Could not download file from '{}': {}\".format(tarball_url, e))",
"\"split\" TARBALL_TYPES = [UNIFIED_TARBALL_TYPE, SPLIT_TARBALL_TYPE] def exit_with_error(error_text): colorprint.error(error_text) sys.exit(1) def",
"{} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest,",
"swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if not is_image_already_imported(manifest[\"fingerprint\"]): print(\"Importing",
"== SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception(\"Tarball type '{}' is",
"manifest[\"tarball_type\"] == SPLIT_TARBALL_TYPE: import_split_image(manifest, alias) else: raise Exception(\"Tarball type '{}'",
"if distro.lower() == \"rhel\": return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def",
"{} -p {}-profile || \" \"lxc launch {} {} -p",
"{}\".format( metadata_tarball_path, rootfs_tarball_path, alias)) os.unlink(metadata_tarball_path) os.unlink(rootfs_tarball_path) def import_image(manifest, alias): '''",
"run_command SCRIPT_DIR = os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume group",
"is_swiftstack_hosted_image(distro): import_image_if_needed(distro) default_image = distro else: default_image = get_default_image(distro) if",
"run_command(\"lxc image import {} {} --alias {}\".format( metadata_tarball_path, rootfs_tarball_path, alias))",
"e: print(\"Could not download file from '{}': {}\".format(url, e)) return",
"os.path.abspath(os.path.dirname(__file__)) # assume well-known lvm volume group on host #",
"delete_image_with_alias(alias) run_command(\"lxc image import {} --alias {}\".format(tarball_path, alias)) os.unlink(tarball_path) def",
"but a method to import \" \"it has not been",
"support both. For unified format, the manifest will look like",
"\" \"/tmp/{}\".format(container_name, VG_NAME, volume_size, volume_count, rand_file_name), cwd=SCRIPT_DIR, shell=True) run_command(\"lxc profile",
"[] for url in [metadata_tarball_url, rootfs_tarball_url]: try: r = requests.get(url,",
"except Exception: pass def download_unified_image_file(manifest): tarball_url = \"{}/{}\".format(SWIFTSTACK_IMAGES_BASE_URL, manifest[\"tarball-object\"]) try:",
"chunk: # filter out keep-alive new chunks f.write(chunk) except Exception",
"not an image hosted by \" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):]",
"distro.lower() == \"rhel\": return \"images:centos/7/amd64\" else: return \"ubuntu:16.04\" def is_swiftstack_hosted_image(base_image):",
"Exception: return False return True def delete_image_with_alias(alias): try: run_command(\"lxc image",
"not download file from '{}': {}\".format(tarball_url, e)) return file_path def",
"be an older image with the same alias delete_image_with_alias(alias) run_command(\"lxc",
"\" \"SwiftStack\".format(base_image)) swift_container_name = base_image[len(SWIFTSTACK_IMAGES_PREFIX):] manifest = get_image_manifest(swift_container_name) if not",
"help='Container distro') parser.add_argument('cname', metavar='containername', help='Container ' 'name') parser.add_argument('volsize', help='Volume size')",
"format, the manifest will look like this: { \"tarball_type\": \"unified\",",
"manifest[\"tarball-object\"]) try: r = requests.get(tarball_url, stream=True) r.raise_for_status() with tempfile.NamedTemporaryFile(delete=False) as",
"|| \" \"lxc launch {} {} -p {}-profile\".format(base_image, container_name, container_name,",
"print(\"Importing image '{}'...\".format(base_image)) import_image(manifest, base_image) else: print(\"Image '{}' is already",
"in [metadata_tarball_url, rootfs_tarball_url]: try: r = requests.get(url, stream=True) r.raise_for_status() with",
"2 possible image formats: unified and split. We support both."
] |
[
"inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e o maximo",
"44, 2, 24, 25])) # print(minimo_e_maximo([88, 66, 10, 2, 8]))",
"len(sequencia) == 1: return primeiro else: menor = r_minimo(sequencia[1:]) return",
"minimo = elem # 2 return minimo, maximo # 1",
"comparações, recursão e funções que sejam de sua autoria. Se",
"pode. Deve informar via docstring qual é a complexidade de",
"4])) # print(minimo_e_maximo([1, 3, 10, 12, 44, 2, 24, 25]))",
"3, 4])) # print(minimo_e_maximo([1, 3, 10, 12, 44, 2, 24,",
"== 1: return primeiro else: maior = r_maximo(sequencia[1:]) return maior",
"também pode. Deve informar via docstring qual é a complexidade",
"elem > maximo: # 2 maximo = elem # 1",
"elem < minimo: # 2 minimo = elem # 2",
"2 minimo = elem # 2 return minimo, maximo #",
"= r_minimo(sequencia[1:]) return menor if menor < primeiro else primeiro",
"sequência numérica aleatória. Complexidade: execução: O(n) espaço: O(3) ''' maximo",
"de uma sequência numérica aleatória. Complexidade: execução: O(n) espaço: O(3)",
"espaço: O(3) ''' maximo = -inf # 1 minimo =",
"primeiro def r_maximo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1:",
"len(sequencia_numerica) == 1: return primeiro, primeiro else: return # print(minimo_e_maximo([1,",
"maximo = -inf # 1 minimo = +inf # 1",
"< primeiro else primeiro def r_maximo(sequencia): primeiro = sequencia[0] if",
"== 1: return primeiro, primeiro else: return # print(minimo_e_maximo([1, 2,",
"# print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1, 3, 10, 12,",
"+inf # 1 for elem in sequencia_numerica: # 1 if",
"numérica aleatória. Só pode usar if, comparações, recursão e funções",
"# 1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro = sequencia[0] if",
"que sejam de sua autoria. Se quiser usar laços também",
"minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e o maximo de uma",
"Só pode usar if, comparações, recursão e funções que sejam",
"retorne min e max de uma sequência numérica aleatória. Só",
"if, comparações, recursão e funções que sejam de sua autoria.",
"de sua autoria. Se quiser usar laços também pode. Deve",
"da sua solução \"\"\" from math import inf def minimo_e_maximo(sequencia_numerica):",
"elem # 2 return minimo, maximo # 1 def recursivo_minmax(sequencia_numerica):",
"1: return primeiro else: menor = r_minimo(sequencia[1:]) return menor if",
"1: return primeiro, primeiro else: return # print(minimo_e_maximo([1, 2, 3,",
"# 1 if elem < minimo: # 2 minimo =",
"# 1 minimo = +inf # 1 for elem in",
"max de uma sequência numérica aleatória. Só pode usar if,",
"return primeiro else: maior = r_maximo(sequencia[1:]) return maior if maior",
"else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0]",
"que retorne min e max de uma sequência numérica aleatória.",
"complexidade de tempo e espaço da sua solução \"\"\" from",
"O(n) espaço: O(3) ''' maximo = -inf # 1 minimo",
"1 for elem in sequencia_numerica: # 1 if elem >",
"minimo: # 2 minimo = elem # 2 return minimo,",
"sequencia_numerica[0] if len(sequencia_numerica) == 1: return primeiro, primeiro else: return",
"e funções que sejam de sua autoria. Se quiser usar",
"def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro = sequencia[0] if len(sequencia) ==",
"aleatória. Complexidade: execução: O(n) espaço: O(3) ''' maximo = -inf",
"primeiro = sequencia[0] if len(sequencia) == 1: return primeiro else:",
"in sequencia_numerica: # 1 if elem > maximo: # 2",
"24, 25])) # print(minimo_e_maximo([88, 66, 10, 2, 8])) print(recursivo_minmax([1, 2,",
"10, 12, 44, 2, 24, 25])) # print(minimo_e_maximo([88, 66, 10,",
"primeiro = sequencia_numerica[0] if len(sequencia_numerica) == 1: return primeiro, primeiro",
"minimo, maximo # 1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro =",
"r_minimo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1: return primeiro",
"len(sequencia) == 1: return primeiro else: maior = r_maximo(sequencia[1:]) return",
"''' maximo = -inf # 1 minimo = +inf #",
"maximo: # 2 maximo = elem # 1 if elem",
"Retorna o minimo e o maximo de uma sequência numérica",
"# 1 for elem in sequencia_numerica: # 1 if elem",
"1 if elem < minimo: # 2 minimo = elem",
"2 return minimo, maximo # 1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia):",
"maximo = elem # 1 if elem < minimo: #",
"Se quiser usar laços também pode. Deve informar via docstring",
"def r_minimo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1: return",
"return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if len(sequencia_numerica)",
"maior if maior > primeiro else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica)",
"primeiro else: return # print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1,",
"def r_maximo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1: return",
"quiser usar laços também pode. Deve informar via docstring qual",
"import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e o",
"menor < primeiro else primeiro def r_maximo(sequencia): primeiro = sequencia[0]",
"recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if len(sequencia_numerica) == 1: return primeiro,",
"1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro = sequencia[0] if len(sequencia)",
"= r_maximo(sequencia[1:]) return maior if maior > primeiro else primeiro",
"uma sequência numérica aleatória. Só pode usar if, comparações, recursão",
"autoria. Se quiser usar laços também pode. Deve informar via",
"> maximo: # 2 maximo = elem # 1 if",
"if len(sequencia) == 1: return primeiro else: menor = r_minimo(sequencia[1:])",
"r_minimo(sequencia[1:]) return menor if menor < primeiro else primeiro def",
"informar via docstring qual é a complexidade de tempo e",
"for elem in sequencia_numerica: # 1 if elem > maximo:",
"elem # 1 if elem < minimo: # 2 minimo",
"usar if, comparações, recursão e funções que sejam de sua",
"math import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e",
"-inf # 1 minimo = +inf # 1 for elem",
"primeiro else: menor = r_minimo(sequencia[1:]) return menor if menor <",
"sequencia[0] if len(sequencia) == 1: return primeiro else: menor =",
"Deve informar via docstring qual é a complexidade de tempo",
"a complexidade de tempo e espaço da sua solução \"\"\"",
"solução \"\"\" from math import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna",
"é a complexidade de tempo e espaço da sua solução",
"laços também pode. Deve informar via docstring qual é a",
"sejam de sua autoria. Se quiser usar laços também pode.",
"1 if elem > maximo: # 2 maximo = elem",
"= sequencia[0] if len(sequencia) == 1: return primeiro else: menor",
"return primeiro, primeiro else: return # print(minimo_e_maximo([1, 2, 3, 4]))",
"menor = r_minimo(sequencia[1:]) return menor if menor < primeiro else",
"# 2 return minimo, maximo # 1 def recursivo_minmax(sequencia_numerica): def",
"def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if len(sequencia_numerica) == 1: return",
"função que retorne min e max de uma sequência numérica",
"minimo = +inf # 1 for elem in sequencia_numerica: #",
"= sequencia_numerica[0] if len(sequencia_numerica) == 1: return primeiro, primeiro else:",
"usar laços também pode. Deve informar via docstring qual é",
"else: maior = r_maximo(sequencia[1:]) return maior if maior > primeiro",
"# 1 if elem > maximo: # 2 maximo =",
"menor if menor < primeiro else primeiro def r_maximo(sequencia): primeiro",
"r_maximo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1: return primeiro",
"e espaço da sua solução \"\"\" from math import inf",
"o minimo e o maximo de uma sequência numérica aleatória.",
"= elem # 1 if elem < minimo: # 2",
"from math import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo",
"25])) # print(minimo_e_maximo([88, 66, 10, 2, 8])) print(recursivo_minmax([1, 2, 3,",
"\"\"\" from math import inf def minimo_e_maximo(sequencia_numerica): ''' Retorna o",
"if len(sequencia_numerica) == 1: return primeiro, primeiro else: return #",
"primeiro else primeiro def r_maximo(sequencia): primeiro = sequencia[0] if len(sequencia)",
"aleatória. Só pode usar if, comparações, recursão e funções que",
"sequencia[0] if len(sequencia) == 1: return primeiro else: maior =",
"e o maximo de uma sequência numérica aleatória. Complexidade: execução:",
"sequência numérica aleatória. Só pode usar if, comparações, recursão e",
"minimo e o maximo de uma sequência numérica aleatória. Complexidade:",
"== 1: return primeiro else: menor = r_minimo(sequencia[1:]) return menor",
"else: menor = r_minimo(sequencia[1:]) return menor if menor < primeiro",
"2, 3, 4])) # print(minimo_e_maximo([1, 3, 10, 12, 44, 2,",
"docstring qual é a complexidade de tempo e espaço da",
"r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if len(sequencia_numerica) == 1:",
"de tempo e espaço da sua solução \"\"\" from math",
"2, 24, 25])) # print(minimo_e_maximo([88, 66, 10, 2, 8])) print(recursivo_minmax([1,",
"recursão e funções que sejam de sua autoria. Se quiser",
"return minimo, maximo # 1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro",
"O(3) ''' maximo = -inf # 1 minimo = +inf",
"uma sequência numérica aleatória. Complexidade: execução: O(n) espaço: O(3) '''",
"1: return primeiro else: maior = r_maximo(sequencia[1:]) return maior if",
"return maior if maior > primeiro else primeiro return r_minimo(sequencia_numerica),",
"e max de uma sequência numérica aleatória. Só pode usar",
"12, 44, 2, 24, 25])) # print(minimo_e_maximo([88, 66, 10, 2,",
"Complexidade: execução: O(n) espaço: O(3) ''' maximo = -inf #",
"maior = r_maximo(sequencia[1:]) return maior if maior > primeiro else",
"maximo # 1 def recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro = sequencia[0]",
"1 minimo = +inf # 1 for elem in sequencia_numerica:",
"# print(minimo_e_maximo([1, 3, 10, 12, 44, 2, 24, 25])) #",
"primeiro else: maior = r_maximo(sequencia[1:]) return maior if maior >",
"print(minimo_e_maximo([1, 3, 10, 12, 44, 2, 24, 25])) # print(minimo_e_maximo([88,",
"primeiro, primeiro else: return # print(minimo_e_maximo([1, 2, 3, 4])) #",
"= +inf # 1 for elem in sequencia_numerica: # 1",
"\"\"\"Criar uma função que retorne min e max de uma",
"maior > primeiro else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica):",
"uma função que retorne min e max de uma sequência",
"2 maximo = elem # 1 if elem < minimo:",
"sua solução \"\"\" from math import inf def minimo_e_maximo(sequencia_numerica): '''",
"via docstring qual é a complexidade de tempo e espaço",
"= elem # 2 return minimo, maximo # 1 def",
"elem in sequencia_numerica: # 1 if elem > maximo: #",
"numérica aleatória. Complexidade: execução: O(n) espaço: O(3) ''' maximo =",
"espaço da sua solução \"\"\" from math import inf def",
"if maior > primeiro else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def",
"de uma sequência numérica aleatória. Só pode usar if, comparações,",
"tempo e espaço da sua solução \"\"\" from math import",
"r_maximo(sequencia[1:]) return maior if maior > primeiro else primeiro return",
"funções que sejam de sua autoria. Se quiser usar laços",
"# print(minimo_e_maximo([88, 66, 10, 2, 8])) print(recursivo_minmax([1, 2, 3, 4]))",
"= -inf # 1 minimo = +inf # 1 for",
"= sequencia[0] if len(sequencia) == 1: return primeiro else: maior",
"o maximo de uma sequência numérica aleatória. Complexidade: execução: O(n)",
"min e max de uma sequência numérica aleatória. Só pode",
"if elem < minimo: # 2 minimo = elem #",
"if len(sequencia) == 1: return primeiro else: maior = r_maximo(sequencia[1:])",
"print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1, 3, 10, 12, 44,",
"# 2 minimo = elem # 2 return minimo, maximo",
"primeiro else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro =",
"pode usar if, comparações, recursão e funções que sejam de",
"def minimo_e_maximo(sequencia_numerica): ''' Retorna o minimo e o maximo de",
"sequencia_numerica: # 1 if elem > maximo: # 2 maximo",
"qual é a complexidade de tempo e espaço da sua",
"recursivo_minmax(sequencia_numerica): def r_minimo(sequencia): primeiro = sequencia[0] if len(sequencia) == 1:",
"r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if len(sequencia_numerica) ==",
"maximo de uma sequência numérica aleatória. Complexidade: execução: O(n) espaço:",
"# 2 maximo = elem # 1 if elem <",
"''' Retorna o minimo e o maximo de uma sequência",
"return primeiro else: menor = r_minimo(sequencia[1:]) return menor if menor",
"return menor if menor < primeiro else primeiro def r_maximo(sequencia):",
"> primeiro else primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro",
"3, 10, 12, 44, 2, 24, 25])) # print(minimo_e_maximo([88, 66,",
"else primeiro def r_maximo(sequencia): primeiro = sequencia[0] if len(sequencia) ==",
"< minimo: # 2 minimo = elem # 2 return",
"if elem > maximo: # 2 maximo = elem #",
"execução: O(n) espaço: O(3) ''' maximo = -inf # 1",
"primeiro return r_minimo(sequencia_numerica), r_maximo(sequencia_numerica) def recursivo_minmax_1x(sequencia_numerica): primeiro = sequencia_numerica[0] if",
"if menor < primeiro else primeiro def r_maximo(sequencia): primeiro =",
"else: return # print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1, 3,",
"sua autoria. Se quiser usar laços também pode. Deve informar",
"return # print(minimo_e_maximo([1, 2, 3, 4])) # print(minimo_e_maximo([1, 3, 10,"
] |
[
"slug = label.replace(\" \", \"\") heading = html.H2( html.Span( [",
"html.H2( html.Span( [ label, html.A( html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\",",
"html.Div( [ heading, dbc.Tooltip( f\"See {label} documentation\", target=f\"tooltip_target_{slug}\" ), ],",
"), ) return html.Div( [ heading, dbc.Tooltip( f\"See {label} documentation\",",
"link): slug = label.replace(\" \", \"\") heading = html.H2( html.Span(",
"= label.replace(\" \", \"\") heading = html.H2( html.Span( [ label,",
"( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link): slug = label.replace(\" \",",
"as dbc import dash_html_components as html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\"",
"dbc import dash_html_components as html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" )",
"DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link): slug =",
"\"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link): slug = label.replace(\" \", \"\")",
"href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ), ) return html.Div( [",
"html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ),",
"html.Span( [ label, html.A( html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\",",
"), ], ), ) return html.Div( [ heading, dbc.Tooltip( f\"See",
"as html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link):",
"], ), ) return html.Div( [ heading, dbc.Tooltip( f\"See {label}",
") def make_subheading(label, link): slug = label.replace(\" \", \"\") heading",
"def make_subheading(label, link): slug = label.replace(\" \", \"\") heading =",
"make_subheading(label, link): slug = label.replace(\" \", \"\") heading = html.H2(",
"dash_bootstrap_components as dbc import dash_html_components as html DBC_DOCS = (",
"\"\") heading = html.H2( html.Span( [ label, html.A( html.I(className=\"fas fa-book",
"import dash_bootstrap_components as dbc import dash_html_components as html DBC_DOCS =",
"heading = html.H2( html.Span( [ label, html.A( html.I(className=\"fas fa-book fa-xs",
"[ heading, dbc.Tooltip( f\"See {label} documentation\", target=f\"tooltip_target_{slug}\" ), ], className=\"mt-3\",",
"html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link): slug",
"label, html.A( html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ),",
") return html.Div( [ heading, dbc.Tooltip( f\"See {label} documentation\", target=f\"tooltip_target_{slug}\"",
"target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ), ) return html.Div( [ heading,",
"dash_html_components as html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label,",
"heading, dbc.Tooltip( f\"See {label} documentation\", target=f\"tooltip_target_{slug}\" ), ], className=\"mt-3\", )",
"id=f\"tooltip_target_{slug}\", ), ], ), ) return html.Div( [ heading, dbc.Tooltip(",
"fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ), ) return",
"label.replace(\" \", \"\") heading = html.H2( html.Span( [ label, html.A(",
"html.A( html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ],",
"fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ), )",
"= ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def make_subheading(label, link): slug = label.replace(\"",
"\", \"\") heading = html.H2( html.Span( [ label, html.A( html.I(className=\"fas",
"= html.H2( html.Span( [ label, html.A( html.I(className=\"fas fa-book fa-xs ml-2\"),",
"import dash_html_components as html DBC_DOCS = ( \"https://dash-bootstrap-components.opensource.faculty.ai/docs/components/\" ) def",
"[ label, html.A( html.I(className=\"fas fa-book fa-xs ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\",",
"return html.Div( [ heading, dbc.Tooltip( f\"See {label} documentation\", target=f\"tooltip_target_{slug}\" ),",
"ml-2\"), href=f\"{DBC_DOCS}{link}\", target=\"_blank\", id=f\"tooltip_target_{slug}\", ), ], ), ) return html.Div("
] |
[
"windows = {} vis = Visdom() def check_availability(vis): # check",
"dict containing options for visdom \"\"\" if name not in",
"= {} windows = {} vis = Visdom() def check_availability(vis):",
"server is not running. Run the server first: python -m",
"given names) or updates an existing window identified by \"name\"",
"window identified by \"name\" :param item: Item to be visualized",
"options for visdom \"\"\" if name not in cls.items_to_visualize: cls.new_item(item,",
"for visdom \"\"\" if name not in cls.items_to_visualize: cls.new_item(item, name,",
"class VisdomLogger: items_iterator = {} items_to_visualize = {} windows =",
"times we # updates this item (stored in items_iterator) X=np.array([cls.items_iterator[name]]),",
") cls.items_iterator[name] += 1 elif isinstance(item, np.ndarray): cls.vis.image( item, opts=args,",
"vis.close() # close visdom check check_availability(vis) @classmethod def visualize(cls, item,",
"**args) else: cls.update_item(item, name, **args) cls.items_to_visualize[name] = item @classmethod def",
"or updates an existing window identified by \"name\" :param item:",
"is running. only once. is_done = vis.text('visdom check') if is_done",
"Item to be visualized (a number or a numpy image).",
"if is_done is False: raise RuntimeError('Visdom server is not running.",
"check check_availability(vis) @classmethod def visualize(cls, item, name, **args): \"\"\" Visualize",
"numbers.Number): cls.items_iterator[name] = 0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name)",
") cls.windows[name] = win else: print(\"type {} not supported for",
"np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name] ) else: print(\"type {} not",
"running. Run the server first: python -m visdom.server') else: print('Visdom",
"cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] = win elif isinstance(item,",
"cls.items_to_visualize[name] = item @classmethod def new_item(cls, item, name, **args): if",
"= win else: print(\"type {} not supported for visualization\".format(type(item))) @classmethod",
"''' The visualization class provides an easy access to some",
"visualize(cls, item, name, **args): \"\"\" Visualize an item in a",
"isinstance(item, numbers.Number): cls.vis.line( # to plot the number we need",
"@classmethod def visualize(cls, item, name, **args): \"\"\" Visualize an item",
"visdom import Visdom import numpy as np import numbers class",
"that will be ploted over time or an image of",
":param args: dict containing options for visdom \"\"\" if name",
"% (vis.server, vis.port)) vis.close() # close visdom check check_availability(vis) @classmethod",
"item @classmethod def new_item(cls, item, name, **args): if isinstance(item, numbers.Number):",
"over time or an image of type np.ndarray ''' from",
"class provides an easy access to some of the visdom",
"= {} vis = Visdom() def check_availability(vis): # check if",
"a number that will be ploted over time or an",
"**args) cls.items_to_visualize[name] = item @classmethod def new_item(cls, item, name, **args):",
"win = cls.vis.image( item, opts=args, ) cls.windows[name] = win else:",
"cls.vis.line( # to plot the number we need to give",
"# to plot the number we need to give its",
"import numbers class VisdomLogger: items_iterator = {} items_to_visualize = {}",
"RuntimeError('Visdom server is not running. Run the server first: python",
"# updates this item (stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name],",
"not supported for visualization\".format(type(item))) @classmethod def update_item(cls, item, name, **args):",
"x axis hence we keep track of how many times",
"else: print(\"type {} not supported for visualization\".format(type(item))) @classmethod def update_item(cls,",
"only once. is_done = vis.text('visdom check') if is_done is False:",
"not on the list of previously given names) or updates",
"number we need to give its position in the x",
"check if the Visdom server is running. only once. is_done",
"window (if the parameter \"name\" is not on the list",
"\"\"\" if name not in cls.items_to_visualize: cls.new_item(item, name, **args) else:",
"= cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] = win elif",
"if isinstance(item, numbers.Number): cls.vis.line( # to plot the number we",
"the item. :param args: dict containing options for visdom \"\"\"",
"by \"name\" :param item: Item to be visualized (a number",
"check') if is_done is False: raise RuntimeError('Visdom server is not",
"the x axis hence we keep track of how many",
"vis.text('visdom check') if is_done is False: raise RuntimeError('Visdom server is",
"name, **args) cls.items_to_visualize[name] = item @classmethod def new_item(cls, item, name,",
"if name not in cls.items_to_visualize: cls.new_item(item, name, **args) else: cls.update_item(item,",
"visualized (a number or a numpy image). :param name: String",
"in cls.items_to_visualize: cls.new_item(item, name, **args) else: cls.update_item(item, name, **args) cls.items_to_visualize[name]",
"in the x axis hence we keep track of how",
"close visdom check check_availability(vis) @classmethod def visualize(cls, item, name, **args):",
"position in the x axis hence we keep track of",
"import numpy as np import numbers class VisdomLogger: items_iterator =",
"available at: %s:%s' % (vis.server, vis.port)) vis.close() # close visdom",
"will be ploted over time or an image of type",
"a new window (if the parameter \"name\" is not on",
"of how many times we # updates this item (stored",
"Visdom import numpy as np import numbers class VisdomLogger: items_iterator",
"np.ndarray): win = cls.vis.image( item, opts=args, ) cls.windows[name] = win",
"as np import numbers class VisdomLogger: items_iterator = {} items_to_visualize",
"items_iterator = {} items_to_visualize = {} windows = {} vis",
") cls.windows[name] = win elif isinstance(item, np.ndarray): win = cls.vis.image(",
"isinstance(item, np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name] ) else: print(\"type {}",
"update='append' ) cls.items_iterator[name] += 1 elif isinstance(item, np.ndarray): cls.vis.image( item,",
"visualization\".format(type(item))) @classmethod def update_item(cls, item, name, **args): if isinstance(item, numbers.Number):",
"= item @classmethod def new_item(cls, item, name, **args): if isinstance(item,",
"at: %s:%s' % (vis.server, vis.port)) vis.close() # close visdom check",
"item: Item to be visualized (a number or a numpy",
"on the list of previously given names) or updates an",
"new_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.items_iterator[name] = 0",
"keep track of how many times we # updates this",
"not running. Run the server first: python -m visdom.server') else:",
"= vis.text('visdom check') if is_done is False: raise RuntimeError('Visdom server",
"print(\"type {} not supported for visualization\".format(type(item))) @classmethod def update_item(cls, item,",
"X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name] += 1 elif isinstance(item,",
":param name: String to identify the item. :param args: dict",
"Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] = win elif isinstance(item, np.ndarray): win",
"= 0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name]",
"The visualization class provides an easy access to some of",
"cls.windows[name] = win elif isinstance(item, np.ndarray): win = cls.vis.image( item,",
"def check_availability(vis): # check if the Visdom server is running.",
"**args): \"\"\" Visualize an item in a new window (if",
"\"name\" is not on the list of previously given names)",
"to identify the item. :param args: dict containing options for",
"previously given names) or updates an existing window identified by",
"identify the item. :param args: dict containing options for visdom",
"we # updates this item (stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]),",
"image of type np.ndarray ''' from visdom import Visdom import",
"def new_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.items_iterator[name] =",
"not in cls.items_to_visualize: cls.new_item(item, name, **args) else: cls.update_item(item, name, **args)",
"X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] = win elif isinstance(item, np.ndarray):",
"visdom functionalities Accept as input a number that will be",
"isinstance(item, np.ndarray): win = cls.vis.image( item, opts=args, ) cls.windows[name] =",
"Run the server first: python -m visdom.server') else: print('Visdom available",
"cls.vis.image( item, opts=args, win=cls.windows[name] ) else: print(\"type {} not supported",
"provides an easy access to some of the visdom functionalities",
"isinstance(item, numbers.Number): cls.items_iterator[name] = 0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]),",
"or an image of type np.ndarray ''' from visdom import",
"= cls.vis.image( item, opts=args, ) cls.windows[name] = win else: print(\"type",
"win elif isinstance(item, np.ndarray): win = cls.vis.image( item, opts=args, )",
"+= 1 elif isinstance(item, np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name] )",
"parameter \"name\" is not on the list of previously given",
"0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] =",
"elif isinstance(item, np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name] ) else: print(\"type",
"numbers.Number): cls.vis.line( # to plot the number we need to",
"check_availability(vis) @classmethod def visualize(cls, item, name, **args): \"\"\" Visualize an",
"for visualization\".format(type(item))) @classmethod def update_item(cls, item, name, **args): if isinstance(item,",
"name, **args): \"\"\" Visualize an item in a new window",
"as input a number that will be ploted over time",
"args: dict containing options for visdom \"\"\" if name not",
"an easy access to some of the visdom functionalities Accept",
"name, **args): if isinstance(item, numbers.Number): cls.items_iterator[name] = 0 win =",
"1 elif isinstance(item, np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name] ) else:",
"\"\"\" Visualize an item in a new window (if the",
"opts=dict(title=name) ) cls.windows[name] = win elif isinstance(item, np.ndarray): win =",
"= Visdom() def check_availability(vis): # check if the Visdom server",
"an existing window identified by \"name\" :param item: Item to",
"{} vis = Visdom() def check_availability(vis): # check if the",
"number or a numpy image). :param name: String to identify",
"name not in cls.items_to_visualize: cls.new_item(item, name, **args) else: cls.update_item(item, name,",
"first: python -m visdom.server') else: print('Visdom available at: %s:%s' %",
"win=cls.windows[name], update='append' ) cls.items_iterator[name] += 1 elif isinstance(item, np.ndarray): cls.vis.image(",
"existing window identified by \"name\" :param item: Item to be",
"be visualized (a number or a numpy image). :param name:",
"numbers class VisdomLogger: items_iterator = {} items_to_visualize = {} windows",
"item. :param args: dict containing options for visdom \"\"\" if",
"update_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.vis.line( # to",
"%s:%s' % (vis.server, vis.port)) vis.close() # close visdom check check_availability(vis)",
"identified by \"name\" :param item: Item to be visualized (a",
"else: cls.update_item(item, name, **args) cls.items_to_visualize[name] = item @classmethod def new_item(cls,",
"elif isinstance(item, np.ndarray): win = cls.vis.image( item, opts=args, ) cls.windows[name]",
"numpy image). :param name: String to identify the item. :param",
"visualization class provides an easy access to some of the",
"is not running. Run the server first: python -m visdom.server')",
"cls.items_iterator[name] = 0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) )",
"item, opts=args, ) cls.windows[name] = win else: print(\"type {} not",
"updates this item (stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append'",
"opts=args, win=cls.windows[name] ) else: print(\"type {} not supported for visualization\".format(type(item)))",
"access to some of the visdom functionalities Accept as input",
"check_availability(vis): # check if the Visdom server is running. only",
"Visdom() def check_availability(vis): # check if the Visdom server is",
"String to identify the item. :param args: dict containing options",
"**args): if isinstance(item, numbers.Number): cls.items_iterator[name] = 0 win = cls.vis.line(",
"def update_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.vis.line( #",
"we need to give its position in the x axis",
"hence we keep track of how many times we #",
"ploted over time or an image of type np.ndarray '''",
"VisdomLogger: items_iterator = {} items_to_visualize = {} windows = {}",
"easy access to some of the visdom functionalities Accept as",
"= {} items_to_visualize = {} windows = {} vis =",
"server is running. only once. is_done = vis.text('visdom check') if",
"visdom \"\"\" if name not in cls.items_to_visualize: cls.new_item(item, name, **args)",
"of previously given names) or updates an existing window identified",
"cls.new_item(item, name, **args) else: cls.update_item(item, name, **args) cls.items_to_visualize[name] = item",
"def visualize(cls, item, name, **args): \"\"\" Visualize an item in",
"cls.items_to_visualize: cls.new_item(item, name, **args) else: cls.update_item(item, name, **args) cls.items_to_visualize[name] =",
"image). :param name: String to identify the item. :param args:",
"name, **args): if isinstance(item, numbers.Number): cls.vis.line( # to plot the",
"names) or updates an existing window identified by \"name\" :param",
"this item (stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' )",
"Visdom server is running. only once. is_done = vis.text('visdom check')",
"is_done = vis.text('visdom check') if is_done is False: raise RuntimeError('Visdom",
"plot the number we need to give its position in",
"time or an image of type np.ndarray ''' from visdom",
"cls.update_item(item, name, **args) cls.items_to_visualize[name] = item @classmethod def new_item(cls, item,",
"\"name\" :param item: Item to be visualized (a number or",
"(stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name] +=",
"''' from visdom import Visdom import numpy as np import",
"an item in a new window (if the parameter \"name\"",
"(vis.server, vis.port)) vis.close() # close visdom check check_availability(vis) @classmethod def",
"be ploted over time or an image of type np.ndarray",
"# close visdom check check_availability(vis) @classmethod def visualize(cls, item, name,",
"new window (if the parameter \"name\" is not on the",
"its position in the x axis hence we keep track",
"some of the visdom functionalities Accept as input a number",
"{} windows = {} vis = Visdom() def check_availability(vis): #",
"(if the parameter \"name\" is not on the list of",
"give its position in the x axis hence we keep",
"the parameter \"name\" is not on the list of previously",
"item (stored in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name]",
"or a numpy image). :param name: String to identify the",
"number that will be ploted over time or an image",
"in items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name] += 1",
"is not on the list of previously given names) or",
"track of how many times we # updates this item",
"in a new window (if the parameter \"name\" is not",
"items_iterator) X=np.array([cls.items_iterator[name]]), Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name] += 1 elif",
"item, name, **args): if isinstance(item, numbers.Number): cls.vis.line( # to plot",
"Visualize an item in a new window (if the parameter",
"name, **args) else: cls.update_item(item, name, **args) cls.items_to_visualize[name] = item @classmethod",
"many times we # updates this item (stored in items_iterator)",
"to plot the number we need to give its position",
"vis = Visdom() def check_availability(vis): # check if the Visdom",
"False: raise RuntimeError('Visdom server is not running. Run the server",
"python -m visdom.server') else: print('Visdom available at: %s:%s' % (vis.server,",
"-m visdom.server') else: print('Visdom available at: %s:%s' % (vis.server, vis.port))",
"updates an existing window identified by \"name\" :param item: Item",
"(a number or a numpy image). :param name: String to",
"<reponame>MathGaron/pytorch_toolbox ''' The visualization class provides an easy access to",
"is_done is False: raise RuntimeError('Visdom server is not running. Run",
"an image of type np.ndarray ''' from visdom import Visdom",
"win else: print(\"type {} not supported for visualization\".format(type(item))) @classmethod def",
"functionalities Accept as input a number that will be ploted",
"of the visdom functionalities Accept as input a number that",
"np import numbers class VisdomLogger: items_iterator = {} items_to_visualize =",
"server first: python -m visdom.server') else: print('Visdom available at: %s:%s'",
"visdom.server') else: print('Visdom available at: %s:%s' % (vis.server, vis.port)) vis.close()",
"else: print('Visdom available at: %s:%s' % (vis.server, vis.port)) vis.close() #",
"supported for visualization\".format(type(item))) @classmethod def update_item(cls, item, name, **args): if",
"numpy as np import numbers class VisdomLogger: items_iterator = {}",
"raise RuntimeError('Visdom server is not running. Run the server first:",
"need to give its position in the x axis hence",
"opts=args, ) cls.windows[name] = win else: print(\"type {} not supported",
"Y=np.array([item]), win=cls.windows[name], update='append' ) cls.items_iterator[name] += 1 elif isinstance(item, np.ndarray):",
"# check if the Visdom server is running. only once.",
"the Visdom server is running. only once. is_done = vis.text('visdom",
"to be visualized (a number or a numpy image). :param",
"the visdom functionalities Accept as input a number that will",
"win = cls.vis.line( X=np.array([cls.items_iterator[name]]), Y=np.array([item]), opts=dict(title=name) ) cls.windows[name] = win",
"list of previously given names) or updates an existing window",
"containing options for visdom \"\"\" if name not in cls.items_to_visualize:",
"from visdom import Visdom import numpy as np import numbers",
"vis.port)) vis.close() # close visdom check check_availability(vis) @classmethod def visualize(cls,",
"to give its position in the x axis hence we",
"print('Visdom available at: %s:%s' % (vis.server, vis.port)) vis.close() # close",
"item, name, **args): \"\"\" Visualize an item in a new",
"= win elif isinstance(item, np.ndarray): win = cls.vis.image( item, opts=args,",
"items_to_visualize = {} windows = {} vis = Visdom() def",
"cls.windows[name] = win else: print(\"type {} not supported for visualization\".format(type(item)))",
"we keep track of how many times we # updates",
"np.ndarray ''' from visdom import Visdom import numpy as np",
"if the Visdom server is running. only once. is_done =",
"is False: raise RuntimeError('Visdom server is not running. Run the",
"@classmethod def update_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.vis.line(",
":param item: Item to be visualized (a number or a",
"name: String to identify the item. :param args: dict containing",
"Accept as input a number that will be ploted over",
"to some of the visdom functionalities Accept as input a",
"how many times we # updates this item (stored in",
"item in a new window (if the parameter \"name\" is",
"import Visdom import numpy as np import numbers class VisdomLogger:",
"input a number that will be ploted over time or",
"once. is_done = vis.text('visdom check') if is_done is False: raise",
"running. only once. is_done = vis.text('visdom check') if is_done is",
"a numpy image). :param name: String to identify the item.",
"{} not supported for visualization\".format(type(item))) @classmethod def update_item(cls, item, name,",
"of type np.ndarray ''' from visdom import Visdom import numpy",
"the server first: python -m visdom.server') else: print('Visdom available at:",
"the number we need to give its position in the",
"@classmethod def new_item(cls, item, name, **args): if isinstance(item, numbers.Number): cls.items_iterator[name]",
"axis hence we keep track of how many times we",
"item, opts=args, win=cls.windows[name] ) else: print(\"type {} not supported for",
"visdom check check_availability(vis) @classmethod def visualize(cls, item, name, **args): \"\"\"",
"type np.ndarray ''' from visdom import Visdom import numpy as",
"**args): if isinstance(item, numbers.Number): cls.vis.line( # to plot the number",
"{} items_to_visualize = {} windows = {} vis = Visdom()",
"item, name, **args): if isinstance(item, numbers.Number): cls.items_iterator[name] = 0 win",
"the list of previously given names) or updates an existing",
"cls.vis.image( item, opts=args, ) cls.windows[name] = win else: print(\"type {}",
"if isinstance(item, numbers.Number): cls.items_iterator[name] = 0 win = cls.vis.line( X=np.array([cls.items_iterator[name]]),",
"cls.items_iterator[name] += 1 elif isinstance(item, np.ndarray): cls.vis.image( item, opts=args, win=cls.windows[name]"
] |
[
"= 1 for i in range(ny): np.random.shuffle(mask[:, i]) # shuffling",
"plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in condition number') plt.xlabel('N_KC') n_kc_claws =",
"as plt # import model def _get_sparse_mask(nx, ny, non, complex=False,",
"for i in range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs =",
"+ np.eye(n_orn) * q # J = np.random.rand(N_PN, N_KC) /",
"= np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds, 'o-')",
"qs] plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction",
"np.linspace(0, 1, 100) conds = [get_logcond(q=q, n_kc=n_kc) for q in",
"n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds = [_get_cond(q, n_orn, n_pn,",
"get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds = [_get_cond(q, n_orn,",
"non connections are 1. Args: nx: int ny: int non:",
"i]) # shuffling in-place return mask.astype(np.float32) def _get_cond(q, n_orn, n_pn,",
"n_kc_claws = np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for n in",
"= np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond def get_logcond(q=1, n_orn=50, n_pn=50,",
"ny, non, complex=False, nOR=50): \"\"\"Generate a binary mask. The mask",
"complex=False, nOR=50): \"\"\"Generate a binary mask. The mask will be",
"i in range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place return mask.astype(np.float32)",
"int ny: int non: int, must not be larger than",
"connections to each 1 of the ny units, only non",
"the ny units, only non connections are 1. Args: nx:",
"must not be larger than nx Return: mask: numpy array",
"in range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place return mask.astype(np.float32) def",
"mask: numpy array (nx, ny) \"\"\" mask = np.zeros((nx, ny))",
"mask = np.zeros((nx, ny)) if not complex: mask[:non] = 1",
"only non connections are 1. Args: nx: int ny: int",
"# J = np.random.randn(N_PN, N_KC) / np.sqrt(N_PN + N_KC) J",
"* mask K = np.dot(M_new, J) # cond = np.linalg.cond(K)",
"= np.logspace(1, 4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for n_kc",
"np.logspace(1, 4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in",
"cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond def get_logcond(q=1, n_orn=50,",
"= np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0,",
"range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1, 100)",
"= [get_logcond(q=q, n_kc=n_kc) for q in qs] plt.figure() plt.plot(qs, conds,",
"plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs),",
"= np.random.randn(N_PN, N_KC) / np.sqrt(N_PN + N_KC) J = np.random.rand(n_pn,",
"1. Args: nx: int ny: int non: int, must not",
"as np import matplotlib.pyplot as plt # import model def",
"ny: int non: int, must not be larger than nx",
"# cond = np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return",
"import numpy as np import matplotlib.pyplot as plt # import",
"n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs)",
"decrease in condition number') plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50) conds",
"plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for n",
"in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs",
"size (nx, ny) For all the nx connections to each",
"mask.astype(np.float32) def _get_cond(q, n_orn, n_pn, n_kc, n_kc_claw): M = np.random.rand(n_orn,",
"number of the network.\"\"\" import numpy as np import matplotlib.pyplot",
"network.\"\"\" import numpy as np import matplotlib.pyplot as plt #",
"n_kcs) plt.ylabel('Log decrease in condition number') plt.xlabel('N_KC') n_kc_claws = np.arange(1,",
"be of size (nx, ny) For all the nx connections",
"than nx Return: mask: numpy array (nx, ny) \"\"\" mask",
"number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4,",
"np.sqrt(N_PN + N_KC) J = np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn,",
"50) conds = np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws,",
"q # J = np.random.rand(N_PN, N_KC) / np.sqrt(N_PN + N_KC)",
"nx Return: mask: numpy array (nx, ny) \"\"\" mask =",
"ny) \"\"\" mask = np.zeros((nx, ny)) if not complex: mask[:non]",
"J = np.random.rand(N_PN, N_KC) / np.sqrt(N_PN + N_KC) # J",
"plt.xlabel('N_KC') n_kcs = np.logspace(1, 4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0)",
"def _get_sparse_mask(nx, ny, non, complex=False, nOR=50): \"\"\"Generate a binary mask.",
"= np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond def",
"conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1, 4, 10).astype(int)",
"n_kc_claw) for i in range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs",
"plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction diagonal')",
"nx connections to each 1 of the ny units, only",
"\"\"\" mask = np.zeros((nx, ny)) if not complex: mask[:non] =",
"conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in condition number') plt.xlabel('N_KC')",
"array (nx, ny) \"\"\" mask = np.zeros((nx, ny)) if not",
"- conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in condition number')",
"nOR=50): \"\"\"Generate a binary mask. The mask will be of",
"(nx, ny) For all the nx connections to each 1",
"' + str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf',",
"plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs =",
"= J * mask K = np.dot(M_new, J) # cond",
"K = np.dot(M_new, J) # cond = np.linalg.cond(K) cond =",
"condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs = np.logspace(1,",
"nx: int ny: int non: int, must not be larger",
"complex: mask[:non] = 1 for i in range(ny): np.random.shuffle(mask[:, i])",
"def plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1, 100) conds = [get_logcond(q=q,",
"a binary mask. The mask will be of size (nx,",
"M * (1-q) + np.eye(n_orn) * q # J =",
"qs = np.linspace(0, 1, 100) conds = [get_logcond(q=q, n_kc=n_kc) for",
"conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs),",
"each 1 of the ny units, only non connections are",
"np.random.rand(n_orn, n_pn) M_new = M * (1-q) + np.eye(n_orn) *",
"diagonal') plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs",
"n_pn, n_kc, n_kc_claw) for i in range(n_rep)] return np.mean(np.log10(conds)) def",
"np.dot(M_new, J) # cond = np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) *",
"+ N_KC) # J = np.random.randn(N_PN, N_KC) / np.sqrt(N_PN +",
"n_kc, n_kc_claw) / n_kc_claw J = J * mask K",
"the network.\"\"\" import numpy as np import matplotlib.pyplot as plt",
"matplotlib.pyplot as plt # import model def _get_sparse_mask(nx, ny, non,",
"* q # J = np.random.rand(N_PN, N_KC) / np.sqrt(N_PN +",
"conds = [_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw) for i in",
"n_kc=n_kc) for q in qs] plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC:",
"# plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4, 10).astype(int)",
"= np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws])",
"numpy array (nx, ny) \"\"\" mask = np.zeros((nx, ny)) if",
"/ np.sqrt(N_PN + N_KC) J = np.random.rand(n_pn, n_kc) mask =",
"np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-')",
"J = J * mask K = np.dot(M_new, J) #",
"n_kc, n_kc_claw) for i in range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500):",
"plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1, 100) conds = [get_logcond(q=q, n_kc=n_kc)",
"mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw J = J",
"10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in n_kcs]) plt.figure()",
"int, must not be larger than nx Return: mask: numpy",
"q=1) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs),",
"will be of size (nx, ny) For all the nx",
"n_pn) M_new = M * (1-q) + np.eye(n_orn) * q",
"+ str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True)",
"np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds, 'o-') plt.xticks(n_kc_claws)",
"\"\"\"Analyze condition number of the network.\"\"\" import numpy as np",
"np.zeros((nx, ny)) if not complex: mask[:non] = 1 for i",
"plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease",
"are 1. Args: nx: int ny: int non: int, must",
"ny) For all the nx connections to each 1 of",
"n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1, 4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc,",
"n_kc, n_kc_claw): M = np.random.rand(n_orn, n_pn) M_new = M *",
"N_KC) # J = np.random.randn(N_PN, N_KC) / np.sqrt(N_PN + N_KC)",
"= [_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw) for i in range(n_rep)]",
"for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs)",
"plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in",
"number') plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for",
"in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure()",
"plt.plot(qs, conds, 'o-') plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log",
"n_kc_claw) / n_kc_claw J = J * mask K =",
"np import matplotlib.pyplot as plt # import model def _get_sparse_mask(nx,",
"np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500,",
"/ n_kc_claw J = J * mask K = np.dot(M_new,",
"conds = [get_logcond(q=q, n_kc=n_kc) for q in qs] plt.figure() plt.plot(qs,",
"n_kcs = np.logspace(1, 4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for",
"non, complex=False, nOR=50): \"\"\"Generate a binary mask. The mask will",
"numpy as np import matplotlib.pyplot as plt # import model",
"for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs)",
"plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 -",
"For all the nx connections to each 1 of the",
"100) conds = [get_logcond(q=q, n_kc=n_kc) for q in qs] plt.figure()",
"not complex: mask[:non] = 1 for i in range(ny): np.random.shuffle(mask[:,",
"_get_sparse_mask(nx, ny, non, complex=False, nOR=50): \"\"\"Generate a binary mask. The",
"the nx connections to each 1 of the ny units,",
"non: int, must not be larger than nx Return: mask:",
"n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC')",
"conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs),",
"np.sqrt(N_PN + N_KC) # J = np.random.randn(N_PN, N_KC) / np.sqrt(N_PN",
"plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1",
"plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1)",
"n_orn, n_pn, n_kc, n_kc_claw): M = np.random.rand(n_orn, n_pn) M_new =",
"+ N_KC) J = np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn, n_kc,",
"def plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc,",
"plt # import model def _get_sparse_mask(nx, ny, non, complex=False, nOR=50):",
"mask[:non] = 1 for i in range(ny): np.random.shuffle(mask[:, i]) #",
"def _get_cond(q, n_orn, n_pn, n_kc, n_kc_claw): M = np.random.rand(n_orn, n_pn)",
"= np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1,",
"n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC')",
"<filename>analytical/conditionnumber.py \"\"\"Analyze condition number of the network.\"\"\" import numpy as",
"* (1-q) + np.eye(n_orn) * q # J = np.random.rand(N_PN,",
"condition number of the network.\"\"\" import numpy as np import",
"10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in n_kcs]) plt.figure()",
"q=0) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs),",
"n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs =",
"plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1, 4, 10).astype(int) conds_q0 =",
"np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond def get_logcond(q=1,",
"cond = np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K) return cond",
"N_KC) J = np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw)",
"J) # cond = np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K)) * np.linalg.norm(K)",
"units, only non connections are 1. Args: nx: int ny:",
"Args: nx: int ny: int non: int, must not be",
"(nx, ny) \"\"\" mask = np.zeros((nx, ny)) if not complex:",
"n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds, 'o-') plt.xticks(n_kc_claws) plt.xlabel('N_KC_claw') plt.show()",
"binary mask. The mask will be of size (nx, ny)",
"N_KC) / np.sqrt(N_PN + N_KC) J = np.random.rand(n_pn, n_kc) mask",
"np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-')",
"all the nx connections to each 1 of the ny",
"ny units, only non connections are 1. Args: nx: int",
"for q in qs] plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC: '",
"n_kc_claw=7, n_rep=10): conds = [_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw) for",
"plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log",
"connections are 1. Args: nx: int ny: int non: int,",
"in range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1,",
"n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds = [_get_cond(q, n_orn, n_pn, n_kc,",
"np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1, 100) conds =",
"'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1, 4, 10).astype(int) conds_q0",
"\"\"\"Generate a binary mask. The mask will be of size",
"to each 1 of the ny units, only non connections",
"J = np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw) /",
"def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds = [_get_cond(q,",
"= np.random.rand(n_orn, n_pn) M_new = M * (1-q) + np.eye(n_orn)",
"of the ny units, only non connections are 1. Args:",
"[get_logcond(q=q, n_kc=n_kc) for q in qs] plt.figure() plt.plot(qs, conds, 'o-')",
"conds_q1 - conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in condition",
"1 for i in range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place",
"n_kc) mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw J =",
"i in range(n_rep)] return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs = np.linspace(0,",
"of size (nx, ny) For all the nx connections to",
"= np.random.rand(N_PN, N_KC) / np.sqrt(N_PN + N_KC) # J =",
"cond def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds =",
"= np.dot(M_new, J) # cond = np.linalg.cond(K) cond = np.linalg.norm(np.linalg.pinv(K))",
"plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4, 10).astype(int) conds_q1",
"= np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw",
"in-place return mask.astype(np.float32) def _get_cond(q, n_orn, n_pn, n_kc, n_kc_claw): M",
"n_kc_claw): M = np.random.rand(n_orn, n_pn) M_new = M * (1-q)",
"(1-q) + np.eye(n_orn) * q # J = np.random.rand(N_PN, N_KC)",
"plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1, 4,",
"n_pn, n_kc, n_kc_claw): M = np.random.rand(n_orn, n_pn) M_new = M",
"4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in n_kcs])",
"larger than nx Return: mask: numpy array (nx, ny) \"\"\"",
"= M * (1-q) + np.eye(n_orn) * q # J",
"be larger than nx Return: mask: numpy array (nx, ny)",
"return np.mean(np.log10(conds)) def plot_cond_by_q(n_kc=2500): qs = np.linspace(0, 1, 100) conds",
"conds = np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds,",
"M = np.random.rand(n_orn, n_pn) M_new = M * (1-q) +",
"np.logspace(1, 4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for n_kc in",
"= _get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw J = J *",
"shuffling in-place return mask.astype(np.float32) def _get_cond(q, n_orn, n_pn, n_kc, n_kc_claw):",
"in condition number') plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50) conds =",
"= np.linspace(0, 1, 100) conds = [get_logcond(q=q, n_kc=n_kc) for q",
"conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0,",
"np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n) for n in n_kc_claws]) plt.figure()",
"not be larger than nx Return: mask: numpy array (nx,",
"int non: int, must not be larger than nx Return:",
"plt.xlabel('fraction diagonal') plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def plot_cond_by_n_kc():",
"plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition number') #",
"n_orn, n_pn, n_kc, n_kc_claw) for i in range(n_rep)] return np.mean(np.log10(conds))",
"model def _get_sparse_mask(nx, ny, non, complex=False, nOR=50): \"\"\"Generate a binary",
"'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.ylabel('Log decrease in condition number') plt.xlabel('N_KC') n_kc_claws",
"plt.ylabel('Log decrease in condition number') plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50)",
"* np.linalg.norm(K) return cond def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7,",
"_get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw J = J * mask",
"n_kcs = np.logspace(1, 4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for",
"import model def _get_sparse_mask(nx, ny, non, complex=False, nOR=50): \"\"\"Generate a",
"mask. The mask will be of size (nx, ny) For",
"Return: mask: numpy array (nx, ny) \"\"\" mask = np.zeros((nx,",
"# import model def _get_sparse_mask(nx, ny, non, complex=False, nOR=50): \"\"\"Generate",
"np.random.rand(n_pn, n_kc) mask = _get_sparse_mask(n_pn, n_kc, n_kc_claw) / n_kc_claw J",
"J * mask K = np.dot(M_new, J) # cond =",
"plt.figure() plt.plot(np.log10(n_kcs), conds_q1, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') n_kcs = np.logspace(1,",
"'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs), conds_q1 - conds_q0, 'o-')",
"for i in range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place return",
"The mask will be of size (nx, ny) For all",
"1 of the ny units, only non connections are 1.",
"mask will be of size (nx, ny) For all the",
"condition number') plt.xlabel('N_KC') n_kc_claws = np.arange(1, 50) conds = np.array([get_logcond(n_kc_claw=n)",
"# J = np.random.rand(N_PN, N_KC) / np.sqrt(N_PN + N_KC) #",
"_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw): M = np.random.rand(n_orn, n_pn) M_new",
"= np.zeros((nx, ny)) if not complex: mask[:non] = 1 for",
"/ np.sqrt(N_PN + N_KC) # J = np.random.randn(N_PN, N_KC) /",
"conds, 'o-') plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition",
"J = np.random.randn(N_PN, N_KC) / np.sqrt(N_PN + N_KC) J =",
"np.random.rand(N_PN, N_KC) / np.sqrt(N_PN + N_KC) # J = np.random.randn(N_PN,",
"np.linalg.norm(K) return cond def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10):",
"return cond def get_logcond(q=1, n_orn=50, n_pn=50, n_kc=2500, n_kc_claw=7, n_rep=10): conds",
"for n in n_kc_claws]) plt.figure() plt.plot(n_kc_claws, conds, 'o-') plt.xticks(n_kc_claws) plt.xlabel('N_KC_claw')",
"np.random.randn(N_PN, N_KC) / np.sqrt(N_PN + N_KC) J = np.random.rand(n_pn, n_kc)",
"n_rep=10): conds = [_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw) for i",
"n_kc=2500, n_kc_claw=7, n_rep=10): conds = [_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw)",
"if not complex: mask[:non] = 1 for i in range(ny):",
"[_get_cond(q, n_orn, n_pn, n_kc, n_kc_claw) for i in range(n_rep)] return",
"n_kc_claw J = J * mask K = np.dot(M_new, J)",
"in qs] plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC: ' + str(n_kc))",
"import matplotlib.pyplot as plt # import model def _get_sparse_mask(nx, ny,",
"str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition number') # plt.savefig('figures/condvsfracdiag_nkc'+str(n_kc)+'.pdf', transparent=True) def",
"ny)) if not complex: mask[:non] = 1 for i in",
"mask K = np.dot(M_new, J) # cond = np.linalg.cond(K) cond",
"transparent=True) def plot_cond_by_n_kc(): n_kcs = np.logspace(1, 4, 10).astype(int) conds_q1 =",
"4, 10).astype(int) conds_q1 = np.array([get_logcond(n_kc=n_kc, q=1) for n_kc in n_kcs])",
"= np.logspace(1, 4, 10).astype(int) conds_q0 = np.array([get_logcond(n_kc=n_kc, q=0) for n_kc",
"q in qs] plt.figure() plt.plot(qs, conds, 'o-') plt.title('N_KC: ' +",
"range(ny): np.random.shuffle(mask[:, i]) # shuffling in-place return mask.astype(np.float32) def _get_cond(q,",
"np.random.shuffle(mask[:, i]) # shuffling in-place return mask.astype(np.float32) def _get_cond(q, n_orn,",
"'o-') plt.title('N_KC: ' + str(n_kc)) plt.xlabel('fraction diagonal') plt.ylabel('log condition number')",
"1, 100) conds = [get_logcond(q=q, n_kc=n_kc) for q in qs]",
"N_KC) / np.sqrt(N_PN + N_KC) # J = np.random.randn(N_PN, N_KC)",
"n_kcs]) plt.figure() plt.plot(np.log10(n_kcs), conds_q0, 'o-') plt.xticks(np.log10(n_kcs), n_kcs) plt.xlabel('N_KC') plt.figure() plt.plot(np.log10(n_kcs),",
"return mask.astype(np.float32) def _get_cond(q, n_orn, n_pn, n_kc, n_kc_claw): M =",
"np.eye(n_orn) * q # J = np.random.rand(N_PN, N_KC) / np.sqrt(N_PN",
"of the network.\"\"\" import numpy as np import matplotlib.pyplot as",
"M_new = M * (1-q) + np.eye(n_orn) * q #",
"# shuffling in-place return mask.astype(np.float32) def _get_cond(q, n_orn, n_pn, n_kc,"
] |
[
"= ('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields",
"rest_framework.authtoken.models import Token from rest_framework import serializers from applications.placement_cell.models import",
"import Token from rest_framework import serializers from applications.placement_cell.models import (Achievement,",
"Course, Education, Experience, Has, Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent)",
"create(self, validated_data): skill = validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill) try:",
"Publication, Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta: model =",
"created = Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill':",
"PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields",
"class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model = NotifyStudent fields = ('__all__')",
"Has, Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class",
"model = Achievement fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta:",
"raise serializers.ValidationError({'skill': 'This skill is already present'}) return has_obj class",
"except: raise serializers.ValidationError({'skill': 'This skill is already present'}) return has_obj",
"Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This skill is already present'}) return",
"import serializers from applications.placement_cell.models import (Achievement, Course, Education, Experience, Has,",
"= Course fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta: model",
"Skill fields = ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class",
"fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta: model = Experience",
"= ('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields",
"= ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class Meta: model",
"fields = ('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course",
"EducationSerializer(serializers.ModelSerializer): class Meta: model = Education fields = ('__all__') class",
"is already present'}) return has_obj class EducationSerializer(serializers.ModelSerializer): class Meta: model",
"PatentSerializer(serializers.ModelSerializer): class Meta: model = Patent fields = ('__all__') class",
"model = NotifyStudent fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id =",
"already present'}) return has_obj class EducationSerializer(serializers.ModelSerializer): class Meta: model =",
"model = PlacementStatus fields = ('notify_id', 'invitation', 'placed', 'timestamp', 'no_of_days')",
"('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement fields =",
"class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class Meta: model = PlacementStatus",
"serializers from applications.placement_cell.models import (Achievement, Course, Education, Experience, Has, Patent,",
"NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model = NotifyStudent fields = ('__all__') class",
"class Meta: model = Project fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer):",
"from rest_framework import serializers from applications.placement_cell.models import (Achievement, Course, Education,",
"('__all__') class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class Meta: model =",
"fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model = NotifyStudent",
"from applications.placement_cell.models import (Achievement, Course, Education, Experience, Has, Patent, Project,",
"class Meta: model = Course fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer):",
"Meta: model = Patent fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class",
"<reponame>29rj/Fusion from rest_framework.authtoken.models import Token from rest_framework import serializers from",
"= ('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement fields",
"fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project",
"class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('__all__')",
"model = Skill fields = ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id =",
"validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except:",
"return has_obj class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education fields",
"model = Course fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta:",
"(Achievement, Course, Education, Experience, Has, Patent, Project, Publication, Skill, PlacementStatus,",
"validated_data): skill = validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill) try: has_obj",
"('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta: model = Experience fields =",
"= SkillSerializer() class Meta: model = Has fields = ('skill_id','skill_rating')",
"Meta: model = Course fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class",
"class AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement fields = ('__all__')",
"class Meta: model = Achievement fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer):",
"Patent fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model =",
"class Meta: model = Publication fields = ('__all__') class PatentSerializer(serializers.ModelSerializer):",
"serializers.ValidationError({'skill': 'This skill is already present'}) return has_obj class EducationSerializer(serializers.ModelSerializer):",
"Project, Publication, Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta: model",
"rest_framework import serializers from applications.placement_cell.models import (Achievement, Course, Education, Experience,",
"SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields = ('__all__') class",
"= Has fields = ('skill_id','skill_rating') def create(self, validated_data): skill =",
"= ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class Meta: model",
"skill = validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill) try: has_obj =",
"class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education fields = ('__all__')",
"class ExperienceSerializer(serializers.ModelSerializer): class Meta: model = Experience fields = ('__all__')",
"Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta:",
"fields = ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class Meta:",
"Meta: model = NotifyStudent fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id",
"= ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta: model = Experience fields",
"class Meta: model = NotifyStudent fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer):",
"Experience, Has, Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer):",
"class Meta: model = Education fields = ('__all__') class CourseSerializer(serializers.ModelSerializer):",
"PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields = ('__all__') class",
"class Meta: model = Skill fields = ('__all__') class HasSerializer(serializers.ModelSerializer):",
"= Achievement fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta: model",
"Education fields = ('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta: model =",
"Meta: model = Experience fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer): class",
"ExperienceSerializer(serializers.ModelSerializer): class Meta: model = Experience fields = ('__all__') class",
"AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement fields = ('__all__') class",
"Meta: model = Achievement fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer): class",
"class Meta: model = Patent fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer):",
"('skill_id','skill_rating') def create(self, validated_data): skill = validated_data.pop('skill_id') skill_id, created =",
"CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('__all__') class",
"has_obj class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education fields =",
"= Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This",
"from rest_framework.authtoken.models import Token from rest_framework import serializers from applications.placement_cell.models",
"fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication",
"'This skill is already present'}) return has_obj class EducationSerializer(serializers.ModelSerializer): class",
"class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields = ('__all__')",
"Achievement fields = ('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta: model =",
"= Publication fields = ('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta: model",
"= ('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields",
"model = Experience fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta:",
"= Patent fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model",
"model = Patent fields = ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta:",
"skill is already present'}) return has_obj class EducationSerializer(serializers.ModelSerializer): class Meta:",
"fields = ('skill_id','skill_rating') def create(self, validated_data): skill = validated_data.pop('skill_id') skill_id,",
"fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement",
"= ('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model = NotifyStudent fields",
"class Meta: model = PlacementStatus fields = ('notify_id', 'invitation', 'placed',",
"Meta: model = PlacementStatus fields = ('notify_id', 'invitation', 'placed', 'timestamp',",
"PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class Meta: model = PlacementStatus fields",
"Token from rest_framework import serializers from applications.placement_cell.models import (Achievement, Course,",
"ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields = ('__all__') class",
"SkillSerializer() class Meta: model = Has fields = ('skill_id','skill_rating') def",
"= Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This skill is already present'})",
"Course fields = ('__all__') class ExperienceSerializer(serializers.ModelSerializer): class Meta: model =",
"('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta: model = Project fields =",
"fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class Meta:",
"Experience fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta: model =",
"= NotifyStudentSerializer() class Meta: model = PlacementStatus fields = ('notify_id',",
"Has fields = ('skill_id','skill_rating') def create(self, validated_data): skill = validated_data.pop('skill_id')",
"applications.placement_cell.models import (Achievement, Course, Education, Experience, Has, Patent, Project, Publication,",
"model = Has fields = ('skill_id','skill_rating') def create(self, validated_data): skill",
"NotifyStudentSerializer() class Meta: model = PlacementStatus fields = ('notify_id', 'invitation',",
"= Education fields = ('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta: model",
"= Experience fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer): class Meta: model",
"NotifyStudent fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class",
"('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta: model = Patent fields =",
"Meta: model = Project fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer): class",
"Project fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta: model =",
"= ('skill_id','skill_rating') def create(self, validated_data): skill = validated_data.pop('skill_id') skill_id, created",
"model = Project fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta:",
"Meta: model = Skill fields = ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id",
"('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer() class Meta: model =",
"notify_id = NotifyStudentSerializer() class Meta: model = PlacementStatus fields =",
"= Skill fields = ('__all__') class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer()",
"class Meta: model = Has fields = ('skill_id','skill_rating') def create(self,",
"Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This skill",
"class PatentSerializer(serializers.ModelSerializer): class Meta: model = Patent fields = ('__all__')",
"class HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class Meta: model = Has",
"HasSerializer(serializers.ModelSerializer): skill_id = SkillSerializer() class Meta: model = Has fields",
"class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields = ('__all__')",
"= validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data)",
"has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This skill is already",
"class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields = ('__all__')",
"Skill, PlacementStatus, NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill",
"try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise serializers.ValidationError({'skill': 'This skill is",
"Meta: model = Publication fields = ('__all__') class PatentSerializer(serializers.ModelSerializer): class",
"('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta: model = Course fields =",
"model = Publication fields = ('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta:",
"= ('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta: model = Patent fields",
"present'}) return has_obj class EducationSerializer(serializers.ModelSerializer): class Meta: model = Education",
"Meta: model = Education fields = ('__all__') class CourseSerializer(serializers.ModelSerializer): class",
"skill_id, created = Skill.objects.get_or_create(**skill) try: has_obj = Has.objects.create(skill_id=skill_id,**validated_data) except: raise",
"= NotifyStudent fields = ('__all__') class PlacementStatusSerializer(serializers.ModelSerializer): notify_id = NotifyStudentSerializer()",
"fields = ('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta: model = Patent",
"Education, Experience, Has, Patent, Project, Publication, Skill, PlacementStatus, NotifyStudent) class",
"NotifyStudent) class SkillSerializer(serializers.ModelSerializer): class Meta: model = Skill fields =",
"import (Achievement, Course, Education, Experience, Has, Patent, Project, Publication, Skill,",
"model = Education fields = ('__all__') class CourseSerializer(serializers.ModelSerializer): class Meta:",
"('__all__') class NotifyStudentSerializer(serializers.ModelSerializer): class Meta: model = NotifyStudent fields =",
"Meta: model = Has fields = ('skill_id','skill_rating') def create(self, validated_data):",
"skill_id = SkillSerializer() class Meta: model = Has fields =",
"('__all__') class PublicationSerializer(serializers.ModelSerializer): class Meta: model = Publication fields =",
"def create(self, validated_data): skill = validated_data.pop('skill_id') skill_id, created = Skill.objects.get_or_create(**skill)",
"Publication fields = ('__all__') class PatentSerializer(serializers.ModelSerializer): class Meta: model =",
"= Project fields = ('__all__') class AchievementSerializer(serializers.ModelSerializer): class Meta: model",
"class Meta: model = Experience fields = ('__all__') class ProjectSerializer(serializers.ModelSerializer):"
] |
[
"import Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta: model = Color",
"Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta: model = Color class",
"Meta: model = Color class AppleFactory(factory.django.DjangoModelFactory): class Meta: model =",
"ColorFactory(factory.django.DjangoModelFactory): class Meta: model = Color class AppleFactory(factory.django.DjangoModelFactory): class Meta:",
"<filename>concat_col_app/factories.py import factory from concat_col_app.models import Color, Apple class ColorFactory(factory.django.DjangoModelFactory):",
"class ColorFactory(factory.django.DjangoModelFactory): class Meta: model = Color class AppleFactory(factory.django.DjangoModelFactory): class",
"class Meta: model = Color class AppleFactory(factory.django.DjangoModelFactory): class Meta: model",
"import factory from concat_col_app.models import Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class",
"model = Color class AppleFactory(factory.django.DjangoModelFactory): class Meta: model = Apple",
"concat_col_app.models import Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta: model =",
"factory from concat_col_app.models import Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta:",
"from concat_col_app.models import Color, Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta: model",
"Apple class ColorFactory(factory.django.DjangoModelFactory): class Meta: model = Color class AppleFactory(factory.django.DjangoModelFactory):"
] |
[
"DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict):",
"self.path: Path = path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int):",
"self.path: str = path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str):",
"super().__init__(f\"directory '{str(path)}' is not a defect taxonomy project\") self.path: Path",
"project\") self.path: Path = path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index:",
"'{value}' (should be KEY=VALUE)\" ) self.value: str = value class",
"import Path from typing import Dict from errors.common.exception import DppError",
"is corrupted: {data}\") self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self,",
"DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}'",
"DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path): super().__init__(f\"directory '{str(path)}' is not a",
"__init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict): super().__init__(f\"config is",
"data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int, name: str, cases:",
"super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict): super().__init__(f\"config is corrupted:",
"def __init__(self, value: str): super().__init__( f\"invalid environment variable format '{value}'",
"def __init__(self, path: str): super().__init__() self.path: str = path class",
"def __init__(self, path: Path): super().__init__(f\"directory '{str(path)}' is not a defect",
"int): super().__init__(f\"invalid index '{index}' of defects\") self.index: int = index",
"path: Path): super().__init__(f\"directory '{str(path)}' is not a defect taxonomy project\")",
"super().__init__(f\"invalid index '{index}' of defects\") self.index: int = index class",
"of defects\") self.index: int = index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def",
"test cases, but expression was: {expr}\" ) self.index: int =",
"value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self,",
"int = index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path: str):",
"'{index}' of defects\") self.index: int = index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError):",
"= index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path: str): super().__init__()",
"class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict): super().__init__(f\"config is corrupted: {data}\")",
"self.name: str = name self.cases: int = cases self.expr: str",
"DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict): super().__init__(f\"config is corrupted: {data}\") self.data",
"variable format '{value}' (should be KEY=VALUE)\" ) self.value: str =",
"= path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int): super().__init__(f\"invalid index",
"f\"Defect#{index} of {name} has {cases} test cases, but expression was:",
"f\"invalid environment variable format '{value}' (should be KEY=VALUE)\" ) self.value:",
"def __init__(self, index: int): super().__init__(f\"invalid index '{index}' of defects\") self.index:",
"Path from typing import Dict from errors.common.exception import DppError class",
") self.index: int = index self.name: str = name self.cases:",
"DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int, name: str, cases: int, expr:",
"super().__init__() self.path: str = path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value:",
"a defect taxonomy project\") self.path: Path = path class DppArgparseDefectIndexError(DppArgparseError):",
"str): super().__init__( f\"invalid environment variable format '{value}' (should be KEY=VALUE)\"",
"= value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def",
"of {name} has {cases} test cases, but expression was: {expr}\"",
"DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path: str): super().__init__() self.path: str =",
"Path = path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int): super().__init__(f\"invalid",
"DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str): super().__init__( f\"invalid environment variable format",
"= data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int, name: str,",
"import Dict from errors.common.exception import DppError class DppArgparseError(DppError): pass class",
"environment variable format '{value}' (should be KEY=VALUE)\" ) self.value: str",
"taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\") self.taxonomy_name: str =",
"str): super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\") self.taxonomy_name: str = taxonomy_name",
"typing import Dict from errors.common.exception import DppError class DppArgparseError(DppError): pass",
"= taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path): super().__init__(f\"directory '{str(path)}'",
"from typing import Dict from errors.common.exception import DppError class DppArgparseError(DppError):",
"def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data: Dict): super().__init__(f\"config",
"class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy",
"str): super().__init__( f\"Defect#{index} of {name} has {cases} test cases, but",
"pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does",
"'{taxonomy_name}' does not exist\") self.taxonomy_name: str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError):",
"__init__(self, value: str): super().__init__( f\"invalid environment variable format '{value}' (should",
"str, cases: int, expr: str): super().__init__( f\"Defect#{index} of {name} has",
"FileNotFoundError): def __init__(self, path: str): super().__init__() self.path: str = path",
"__init__(self, path: Path): super().__init__(f\"directory '{str(path)}' is not a defect taxonomy",
"def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\") self.taxonomy_name:",
"str = name self.cases: int = cases self.expr: str =",
"= index self.name: str = name self.cases: int = cases",
"taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path): super().__init__(f\"directory '{str(path)}' is",
"class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path): super().__init__(f\"directory '{str(path)}' is not",
"def __init__(self, data: Dict): super().__init__(f\"config is corrupted: {data}\") self.data =",
"defect taxonomy project\") self.path: Path = path class DppArgparseDefectIndexError(DppArgparseError): def",
"{cases} test cases, but expression was: {expr}\" ) self.index: int",
"self.index: int = index self.name: str = name self.cases: int",
"self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int, name:",
"corrupted: {data}\") self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index:",
"{expr}\" ) self.index: int = index self.name: str = name",
"Dict from errors.common.exception import DppError class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError):",
"self.value: str = value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class",
"DppError class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str):",
"{data}\") self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int,",
"__init__(self, path: str): super().__init__() self.path: str = path class DppArgparseInvalidEnvironment(DppArgparseError):",
"defects\") self.index: int = index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self,",
"{name} has {cases} test cases, but expression was: {expr}\" )",
"errors.common.exception import DppError class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self,",
"KEY=VALUE)\" ) self.value: str = value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self):",
"int, name: str, cases: int, expr: str): super().__init__( f\"Defect#{index} of",
"index '{index}' of defects\") self.index: int = index class DppArgparseFileNotFoundError(DppArgparseError,",
"from errors.common.exception import DppError class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def",
"import DppError class DppArgparseError(DppError): pass class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name:",
"not exist\") self.taxonomy_name: str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self,",
"str = path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str): super().__init__(",
"__init__(self, index: int, name: str, cases: int, expr: str): super().__init__(",
"value: str): super().__init__( f\"invalid environment variable format '{value}' (should be",
") self.value: str = value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__()",
"Dict): super().__init__(f\"config is corrupted: {data}\") self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError):",
"expr: str): super().__init__( f\"Defect#{index} of {name} has {cases} test cases,",
"index self.name: str = name self.cases: int = cases self.expr:",
"has {cases} test cases, but expression was: {expr}\" ) self.index:",
"= path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str): super().__init__( f\"invalid",
"exist\") self.taxonomy_name: str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path:",
"index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path: str): super().__init__() self.path:",
"cases: int, expr: str): super().__init__( f\"Defect#{index} of {name} has {cases}",
"str): super().__init__() self.path: str = path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self,",
"def __init__(self, index: int, name: str, cases: int, expr: str):",
"int = index self.name: str = name self.cases: int =",
"'{str(path)}' is not a defect taxonomy project\") self.path: Path =",
"cases, but expression was: {expr}\" ) self.index: int = index",
"class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path: str): super().__init__() self.path: str",
"class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError): def __init__(self, data:",
"__init__(self, data: Dict): super().__init__(f\"config is corrupted: {data}\") self.data = data",
"= name self.cases: int = cases self.expr: str = expr",
"does not exist\") self.taxonomy_name: str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def",
"was: {expr}\" ) self.index: int = index self.name: str =",
"Path): super().__init__(f\"directory '{str(path)}' is not a defect taxonomy project\") self.path:",
"taxonomy project\") self.path: Path = path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self,",
"int, expr: str): super().__init__( f\"Defect#{index} of {name} has {cases} test",
"data: Dict): super().__init__(f\"config is corrupted: {data}\") self.data = data class",
"index: int, name: str, cases: int, expr: str): super().__init__( f\"Defect#{index}",
"super().__init__( f\"Defect#{index} of {name} has {cases} test cases, but expression",
"but expression was: {expr}\" ) self.index: int = index self.name:",
"from pathlib import Path from typing import Dict from errors.common.exception",
"super().__init__( f\"invalid environment variable format '{value}' (should be KEY=VALUE)\" )",
"__init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\") self.taxonomy_name: str",
"DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\")",
"str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path): super().__init__(f\"directory",
"class DppArgparseInvalidCaseExpressionError(DppArgparseError): def __init__(self, index: int, name: str, cases: int,",
"class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str): super().__init__( f\"invalid environment variable",
"DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int): super().__init__(f\"invalid index '{index}' of defects\")",
"(should be KEY=VALUE)\" ) self.value: str = value class DppArgparseInvalidConfigError(DppArgparseError):",
"super().__init__(f\"taxonomy '{taxonomy_name}' does not exist\") self.taxonomy_name: str = taxonomy_name class",
"__init__(self, index: int): super().__init__(f\"invalid index '{index}' of defects\") self.index: int",
"is not a defect taxonomy project\") self.path: Path = path",
"path: str): super().__init__() self.path: str = path class DppArgparseInvalidEnvironment(DppArgparseError): def",
"class DppArgparseTaxonomyNotFoundError(DppArgparseError): def __init__(self, taxonomy_name: str): super().__init__(f\"taxonomy '{taxonomy_name}' does not",
"path class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int): super().__init__(f\"invalid index '{index}'",
"str = value class DppArgparseInvalidConfigError(DppArgparseError): def __init__(self): super().__init__() class DppArgparseConfigCorruptedError(DppArgparseError):",
"expression was: {expr}\" ) self.index: int = index self.name: str",
"be KEY=VALUE)\" ) self.value: str = value class DppArgparseInvalidConfigError(DppArgparseError): def",
"path class DppArgparseInvalidEnvironment(DppArgparseError): def __init__(self, value: str): super().__init__( f\"invalid environment",
"self.taxonomy_name: str = taxonomy_name class DppArgparseNotProjectDirectory(DppArgparseError): def __init__(self, path: Path):",
"not a defect taxonomy project\") self.path: Path = path class",
"name: str, cases: int, expr: str): super().__init__( f\"Defect#{index} of {name}",
"super().__init__(f\"config is corrupted: {data}\") self.data = data class DppArgparseInvalidCaseExpressionError(DppArgparseError): def",
"self.index: int = index class DppArgparseFileNotFoundError(DppArgparseError, FileNotFoundError): def __init__(self, path:",
"format '{value}' (should be KEY=VALUE)\" ) self.value: str = value",
"index: int): super().__init__(f\"invalid index '{index}' of defects\") self.index: int =",
"class DppArgparseDefectIndexError(DppArgparseError): def __init__(self, index: int): super().__init__(f\"invalid index '{index}' of",
"pathlib import Path from typing import Dict from errors.common.exception import"
] |
[
"from .resume import * from .optims import * from .metric",
"* from .tricks import * from .tensorlog import * from",
".utility import * from .tricks import * from .tensorlog import",
".self_op import * from .resume import * from .optims import",
"import * from .tensorlog import * from .self_op import *",
"* from .self_op import * from .resume import * from",
"from .utility import * from .tricks import * from .tensorlog",
"* from .tensorlog import * from .self_op import * from",
".tensorlog import * from .self_op import * from .resume import",
"from .tensorlog import * from .self_op import * from .resume",
"from .self_op import * from .resume import * from .optims",
"import * from .self_op import * from .resume import *",
".resume import * from .optims import * from .metric import",
"import * from .optims import * from .metric import *",
"import * from .resume import * from .optims import *",
"* from .resume import * from .optims import * from",
".tricks import * from .tensorlog import * from .self_op import",
"import * from .tricks import * from .tensorlog import *",
"from .tricks import * from .tensorlog import * from .self_op"
] |
[
"Corporation Licensed under the Apache License, Version 2.0 (the \"License\");",
"permissions and limitations under the License. \"\"\" import numpy as",
"attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start', 0), 'stop': attrs.int('stop',",
"op = '_arange' enabled = True @classmethod def extract(cls, node:",
"= '_arange' enabled = True @classmethod def extract(cls, node: Node):",
"Unless required by applicable law or agreed to in writing,",
"by applicable law or agreed to in writing, software distributed",
"from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import Node class ArangeExt(FrontExtractorOp):",
"(C) 2018-2021 Intel Corporation Licensed under the Apache License, Version",
"ArangeExt(FrontExtractorOp): op = '_arange' enabled = True @classmethod def extract(cls,",
"software distributed under the License is distributed on an \"AS",
"distributed under the License is distributed on an \"AS IS\"",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"limitations under the License. \"\"\" import numpy as np from",
"Version 2.0 (the \"License\"); you may not use this file",
"import get_mxnet_layer_attrs from mo.graph.graph import Node class ArangeExt(FrontExtractorOp): op =",
"writing, software distributed under the License is distributed on an",
"'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1), 'step': attrs.float('step', 1), 'dtype':",
"'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype ', 'float32')) }) return cls.enabled",
"not use this file except in compliance with the License.",
"2.0 (the \"License\"); you may not use this file except",
"Apache License, Version 2.0 (the \"License\"); you may not use",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"express or implied. See the License for the specific language",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"License. \"\"\" import numpy as np from extensions.ops.range import Range",
"from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph",
"in compliance with the License. You may obtain a copy",
"class ArangeExt(FrontExtractorOp): op = '_arange' enabled = True @classmethod def",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"you may not use this file except in compliance with",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"the License. You may obtain a copy of the License",
"agreed to in writing, software distributed under the License is",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"True @classmethod def extract(cls, node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node,",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"use this file except in compliance with the License. You",
"1), 'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype ', 'float32')) }) return",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"ANY KIND, either express or implied. See the License for",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"get_mxnet_layer_attrs from mo.graph.graph import Node class ArangeExt(FrontExtractorOp): op = '_arange'",
"Node class ArangeExt(FrontExtractorOp): op = '_arange' enabled = True @classmethod",
"Range from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from",
"either express or implied. See the License for the specific",
"0), 'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1), 'step': attrs.float('step', 1),",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"under the License is distributed on an \"AS IS\" BASIS,",
"\"License\"); you may not use this file except in compliance",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"Licensed under the Apache License, Version 2.0 (the \"License\"); you",
"0), 'repeat': attrs.int('repeat', 1), 'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype ',",
"with the License. You may obtain a copy of the",
"@classmethod def extract(cls, node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, {",
"Range.update_node_stat(node, { 'start': attrs.int('start', 0), 'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat',",
"def extract(cls, node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start':",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"License for the specific language governing permissions and limitations under",
"FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import Node class",
"attrs.int('start', 0), 'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1), 'step': attrs.float('step',",
"this file except in compliance with the License. You may",
"'start': attrs.int('start', 0), 'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1), 'step':",
"specific language governing permissions and limitations under the License. \"\"\"",
"(the \"License\"); you may not use this file except in",
"node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start', 0),",
"mo.graph.graph import Node class ArangeExt(FrontExtractorOp): op = '_arange' enabled =",
"enabled = True @classmethod def extract(cls, node: Node): attrs =",
"Copyright (C) 2018-2021 Intel Corporation Licensed under the Apache License,",
"applicable law or agreed to in writing, software distributed under",
"as np from extensions.ops.range import Range from mo.front.extractor import FrontExtractorOp",
"get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start', 0), 'stop': attrs.int('stop', 0), 'repeat':",
"= get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start', 0), 'stop': attrs.int('stop', 0),",
"and limitations under the License. \"\"\" import numpy as np",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"the specific language governing permissions and limitations under the License.",
"numpy as np from extensions.ops.range import Range from mo.front.extractor import",
"the Apache License, Version 2.0 (the \"License\"); you may not",
"file except in compliance with the License. You may obtain",
"except in compliance with the License. You may obtain a",
"or implied. See the License for the specific language governing",
"KIND, either express or implied. See the License for the",
"attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1), 'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype",
"to in writing, software distributed under the License is distributed",
"import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import Node",
"or agreed to in writing, software distributed under the License",
"Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start', 0), 'stop':",
"law or agreed to in writing, software distributed under the",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"2018-2021 Intel Corporation Licensed under the Apache License, Version 2.0",
"{ 'start': attrs.int('start', 0), 'stop': attrs.int('stop', 0), 'repeat': attrs.int('repeat', 1),",
"compliance with the License. You may obtain a copy of",
"\"\"\" import numpy as np from extensions.ops.range import Range from",
"= True @classmethod def extract(cls, node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict)",
"language governing permissions and limitations under the License. \"\"\" import",
"OF ANY KIND, either express or implied. See the License",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"from mo.graph.graph import Node class ArangeExt(FrontExtractorOp): op = '_arange' enabled",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"'repeat': attrs.int('repeat', 1), 'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype ', 'float32'))",
"\"\"\" Copyright (C) 2018-2021 Intel Corporation Licensed under the Apache",
"the License. \"\"\" import numpy as np from extensions.ops.range import",
"extract(cls, node: Node): attrs = get_mxnet_layer_attrs(node.symbol_dict) Range.update_node_stat(node, { 'start': attrs.int('start',",
"under the License. \"\"\" import numpy as np from extensions.ops.range",
"License, Version 2.0 (the \"License\"); you may not use this",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"Intel Corporation Licensed under the Apache License, Version 2.0 (the",
"for the specific language governing permissions and limitations under the",
"See the License for the specific language governing permissions and",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"governing permissions and limitations under the License. \"\"\" import numpy",
"extensions.ops.range import Range from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import",
"import Node class ArangeExt(FrontExtractorOp): op = '_arange' enabled = True",
"License. You may obtain a copy of the License at",
"the License for the specific language governing permissions and limitations",
"may not use this file except in compliance with the",
"in writing, software distributed under the License is distributed on",
"required by applicable law or agreed to in writing, software",
"implied. See the License for the specific language governing permissions",
"mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import Node class ArangeExt(FrontExtractorOp): op",
"'_arange' enabled = True @classmethod def extract(cls, node: Node): attrs",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"attrs.int('repeat', 1), 'step': attrs.float('step', 1), 'dtype': np.dtype(attrs.str('dtype ', 'float32')) })",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"import numpy as np from extensions.ops.range import Range from mo.front.extractor",
"np from extensions.ops.range import Range from mo.front.extractor import FrontExtractorOp from",
"mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs from mo.graph.graph import",
"from extensions.ops.range import Range from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils",
"import Range from mo.front.extractor import FrontExtractorOp from mo.front.mxnet.extractors.utils import get_mxnet_layer_attrs"
] |
[
"np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum =",
"= glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*') if 'innm'",
"parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to",
"or test, or both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to",
"aug_num = train_count['normal'] // train_count['noonan'] - 1 for img in",
"print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered: for img_f in",
"# verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f)))",
"targets, args.tta) label = score_names[-1] score = np.exp(distance.dot(-1)) pred =",
"color='darkorange', lw=lw, label='ROC curve (area = %0.4f)' % roc_auc) plt.plot([0,",
"args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name += '_lag' elif 'literature'",
"for i in range(n_classes): score_sum += score_np[:, i, None] #",
"splitting iterations in the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training",
"'_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan',",
"exp_name += '_ltr' if args.kfold != 10: exp_name += ('_k'",
"'/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir =",
"seed used for k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether",
"'innm' in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/'",
"plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() #",
"parser.add_argument(\"-ac\", \"--arch\", help=\"types of model used for encoder\", default=\"mobile\", type=str)",
"full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf =",
"kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split raw",
"in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in names_idx.keys(): if",
"Process, Pipe,Value,Array import torch from config import get_config from mtcnn",
"for p in prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*')",
"== '__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where",
"[] args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not",
"save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve and ROC area",
"os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name]",
"from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics",
"names_idx = prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:', names)",
"= roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) #",
"(score_np / score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path",
"str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\"",
"os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) + '/' +",
"test_dir.iterdir(): if path.is_file(): continue # print(path) for fil in path.iterdir():",
"loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if",
"= ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for",
"count unbalanced data train_count = {} test_count = {} for",
"colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw,",
"= %0.4f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw,",
"score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep + '/pr_{}.png'.format(exp_name)) plt.close()",
"pred != label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names =",
"color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate')",
"= os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold",
"in stylegan_folders): # and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for",
"\"but 0 means retraining the whole network.\", default=0, type=int) parser.add_argument(\"-ac\",",
"test, or both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s)",
"# plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05])",
"split raw data data_dict = {} idx_gen = {} for",
"'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] =",
"= (score_np / score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel()",
"img_folder = str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep",
"default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different types considered, separated",
"0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.')",
"= Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf, faces, targets,",
"name in names_considered: for img_f in add_data: if name in",
"= np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'],",
"str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' +",
"help=\"use stylegan data in only train, or test, or both\",",
"default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to use\", default=\"\", type=str)",
"tta = args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated')",
"type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number of splitting iterations in",
"parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different types considered, separated by commas\",",
"exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders =",
"from config import get_config from mtcnn import MTCNN from Learner_trans_tf",
"= {} test_count = {} for name in names_considered: train_count[name]",
"shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered:",
"faces = [image,] distance = learner.binfer(conf, faces, targets, args.tta) label",
"tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.4f)' % roc_auc)",
"score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path,",
"help=\"names for different types considered, separated by commas\", default=\"normal,noonan,others\", type=str)",
"type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to use\", default=\"\", type=str) parser.add_argument(\"-s\",",
"help=\"where to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\",",
"stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name])",
"import matplotlib.pyplot as plt import matplotlib.colors as mcolors import datetime",
"+ '/train/' + name + os.sep + img)) train_count[name] +=",
"img)) train_count[name] += 1 # test for i in range(len(test_set[name])):",
"args.additional_data_dir, len(add_data)) for name in names_considered: for img_f in add_data:",
"20: exp_name += ('_e' + str(args.epochs)) if args.transfer != 0",
"exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s'",
"learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is saved') # prepare_facebank",
"+= '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir",
"kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*'))",
"'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!')",
"['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir,",
"fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in names_idx.keys(): if name",
"names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name not",
"np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores",
"fil.name) continue \"\"\" frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces",
"sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold",
"iterations in the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\",",
"name in names_considered: train_count[name] = 0 for i in range(len(train_set[name])):",
"data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data in only",
"1 # addition data from stylegan if 'interp' not in",
"stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir,",
"# keep the dimension relative_scores = (score_np / score_sum) total_scores",
"parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data in only train, or test,",
"str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) #",
"+ name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir)",
"from sklearn.model_selection import KFold import os import glob import shutil",
"plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.4f)' %",
"conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered =",
"os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names)",
"'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] =",
"img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if 'fake' in args.additional_data_dir: fake_dict",
"= parser.parse_args() for arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir",
"relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names)",
"= np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum += score_np[:,",
"str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count, test_count) #",
"curve (area = %0.4f)' % roc_auc) plt.plot([0, 1], [0, 1],",
"total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy')",
"= kf.split(data_dict['ltr']) score_names = [] scores = [] wrong_names =",
"{} for name in names_considered: train_count[name] = 0 for i",
"help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different types",
"# addition data from stylegan if 'interp' not in data_dict.keys():",
"os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 # addition data from",
"data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if",
"2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area = %0.4f)'",
"args.transfer != 0 and args.transfer != 1: exp_name += ('_td'",
"= conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir):",
"linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive",
"\"\"\" frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,]",
"= os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder",
"+= '_ltr' if args.kfold != 10: exp_name += ('_k' +",
"= {} idx_gen = {} for name in names_considered: tmp_list",
"full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png')",
"faces, targets, args.tta) label = score_names[-1] score = np.exp(distance.dot(-1)) pred",
"os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx",
"= os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path,",
"(train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set =",
"+ str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 # addition",
"both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s) used for",
"# deal with unbalanced data \"\"\" if train_count['normal'] // train_count['noonan']",
"additional data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data in",
"raw data data_dict = {} idx_gen = {} for name",
"data from stylegan if 'interp' not in data_dict.keys(): folder =",
"default=\"mobile\", type=str) args = parser.parse_args() for arg in vars(args): print(arg+':',",
"('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed))",
"'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' #",
"retrained.') learner.save_state() print('Model is saved') # prepare_facebank targets, names, names_idx",
"in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data",
"= conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir):",
"if 'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir",
"= [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if",
"= conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path =",
"parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for",
"os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name,",
"for path in test_dir.iterdir(): if path.is_file(): continue # print(path) for",
"test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev =",
"help=\"how many layer(s) used for transfer learning, \" \"but 0",
"\"--gpu_id\", help=\"gpu id to use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether",
"list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve",
"str(args.kfold)) if args.epochs != 20: exp_name += ('_e' + str(args.epochs))",
"idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir)",
"folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and",
"i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in os.listdir(img_folder):",
"str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type + '/train/'",
"# tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count =",
"plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange',",
"additional data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data in",
"str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img),",
"KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) #",
"= str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep +",
"help=\"where to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\",",
"add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy",
"1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path",
"test_count) # deal with unbalanced data \"\"\" if train_count['normal'] //",
"score_np[:, i, None] # keep the dimension relative_scores = (score_np",
"{} idx_gen = {} for name in names_considered: tmp_list =",
"in the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20,",
"types considered, separated by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu",
"= KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split raw data",
"if args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train,",
"conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name",
"= next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in",
"i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in names_idx.keys():",
"label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy')",
"print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is saved')",
"Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep",
"train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) #",
"the additional data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data",
"if __name__ == '__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\",",
"= [] scores = [] wrong_names = [] args.stored_result_path =",
"prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and # tests",
"# for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in",
"name in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] =",
"np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum += score_np[:, i,",
"%0.4f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--')",
"exp_name += ('_s' + str(args.random_seed)) print(exp_name) # prepare folders raw_dir",
"import face_learner from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize",
"verify_type = 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir",
"shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if 'fake' in",
"score_sum = np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum +=",
"in only train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-as\",",
"args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered",
"(area = %0.4f)' % roc_auc) plt.plot([0, 1], [0, 1], color='navy',",
"data in only train, or test, or both\", default=\"\", type=str)",
"to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use",
"conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN()",
"label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection",
"different types considered, separated by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\",",
"\"--stylegan_data_dir\", help=\"where to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ts\",",
"to store data as np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\",",
"(folder in stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep +",
"[] wrong_names = [] args.stored_result_path = args.stored_result_dir + os.sep +",
"'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir",
"args.epochs != 20: exp_name += ('_e' + str(args.epochs)) if args.transfer",
"args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path):",
"for k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time",
"use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used for",
"data \"\"\" if train_count['normal'] // train_count['noonan'] > 1: aug_num =",
"os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder =",
"name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train =",
"# save trains to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test'",
"= next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in",
"\"--epochs\", help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different",
"utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import",
"{'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep",
"or test, or both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many",
"shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count,",
"[] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature'",
"+ os.sep + img)) train_count[name] += 1 # test for",
"test_count[name] = 0 img_folder = str(test_set[name][i]) for img in os.listdir(img_folder):",
"face_learner from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from",
"data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr']))",
"# and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in",
"in stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep + folder):",
"torch from config import get_config from mtcnn import MTCNN from",
"type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of model used for encoder\", default=\"mobile\",",
"prev = glob.glob(str(test_dir) + '/*/*') for p in prev: os.remove(p)",
"+ '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered: for",
"verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx)",
"continue # print(path) for fil in path.iterdir(): # print(fil) orig_name",
"''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name",
"+= score_np[:, i, None] # keep the dimension relative_scores =",
"= auc(fpr, tpr) # For PR curve precision, recall, _",
"os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type +",
"type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data in only train, or",
"name + os.sep + img)) train_count[name] += 1 # test",
"noonan_idx = names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir(): if",
"+ str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 # addition",
"print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf = get_config(True, args)",
"matplotlib.pyplot as plt import matplotlib.colors as mcolors import datetime if",
"+ '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name]",
"plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show()",
"print(\"Un-considered name:\", fil.name) continue \"\"\" frame = cv2.imread(str(fil)) image =",
"\"--tta\", help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get",
"names) noonan_idx = names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir():",
"= args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated') for",
"wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names",
"= prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx",
"type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s) used for transfer learning,",
"= data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index) =",
"save_label_score, label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from",
"kf.split(data_dict['ltr']) score_names = [] scores = [] wrong_names = []",
"name, str(img))) test_count[name] += 1 print(train_count, test_count) # deal with",
"range(aug_num): aug_img = img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):]",
"= score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if",
"stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if",
"in add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) #",
"fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set",
"not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train'",
"+ os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in",
"from pathlib import Path from multiprocessing import Process, Pipe,Value,Array import",
"get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded')",
"pathlib import Path from multiprocessing import Process, Pipe,Value,Array import torch",
"[0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False",
"type=str) args = parser.parse_args() for arg in vars(args): print(arg+':', getattr(args,",
"next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train:",
"train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan']",
"conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count = {} test_count =",
"in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder",
"label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i in range(n_classes):",
"= args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name +=",
"mtcnn import MTCNN from Learner_trans_tf import face_learner from utils import",
"= {} for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) +",
"str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 # addition data",
"import Image import argparse from pathlib import Path from multiprocessing",
"import argparse from pathlib import Path from multiprocessing import Process,",
"glob import shutil import numpy as np import matplotlib.pyplot as",
"'noonan', aug_img)) \"\"\" if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal',",
"range(args.kfold): train_set = {} test_set = {} for name in",
"recall, _ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) #",
"# plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr,",
"if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder in stylegan_folders):",
"orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()])",
"np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred != label: wrong_names.append(orig_name)",
"= MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4]",
"print(train_count, test_count) # deal with unbalanced data \"\"\" if train_count['normal']",
"p in prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and",
"roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) # For",
"in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name, str(img)))",
"# init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed)",
"if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) +",
"+ str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index,",
"\"\"\" if train_count['normal'] // train_count['noonan'] > 1: aug_num = train_count['normal']",
"# (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir +",
"sklearn.model_selection import KFold import os import glob import shutil import",
"for encoder\", default=\"mobile\", type=str) args = parser.parse_args() for arg in",
"test_count[name] += 1 print(train_count, test_count) # deal with unbalanced data",
"True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is",
"and ROC area for noonan fpr, tpr, _ = roc_curve(total_names,",
"1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\")",
"+= ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' +",
"cv2 from PIL import Image import argparse from pathlib import",
"conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir)",
"plt import matplotlib.colors as mcolors import datetime if __name__ ==",
"not i.isdigit()]) for name in names_idx.keys(): if name in orig_name:",
"__name__ == '__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\",",
"help=\"where to get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data",
"= cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,] distance =",
"arg)) emore_dir = 'faces_emore' conf = get_config(True, args) conf.emore_folder =",
"np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1]",
"import numpy as np import matplotlib.pyplot as plt import matplotlib.colors",
"model used for encoder\", default=\"mobile\", type=str) args = parser.parse_args() for",
"+= ('_s' + str(args.random_seed)) print(exp_name) # prepare folders raw_dir =",
"tpr) # For PR curve precision, recall, _ = precision_recall_curve(total_names,",
"= {} test_set = {} for name in names_considered: (train_index,",
"(train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if",
"epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different types considered,",
"+ name + '*') if 'innm' in args.stylegan_data_dir: tmp_list =",
"= conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:',",
"names_considered: for img_f in add_data: if name in img_f.strip().split(os.sep)[-1]: #",
"names_considered: print(\"Un-considered name:\", fil.name) continue \"\"\" frame = cv2.imread(str(fil)) image",
"prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta =",
"used for encoder\", default=\"mobile\", type=str) args = parser.parse_args() for arg",
"[] scores = [] wrong_names = [] args.stored_result_path = args.stored_result_dir",
"mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank",
"# print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name]))",
"from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i])",
"tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count = {}",
"prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx =",
"in names_considered: print(\"Un-considered name:\", fil.name) continue \"\"\" frame = cv2.imread(str(fil))",
"1) if pred != label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names)",
"_ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) # plots",
"i.isdigit()]) for name in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name])",
"# prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta",
"# conf, inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False,",
"if args.kfold != 10: exp_name += ('_k' + str(args.kfold)) if",
"learner.save_state() print('Model is saved') # prepare_facebank targets, names, names_idx =",
"dimension relative_scores = (score_np / score_sum) total_scores = relative_scores.ravel() total_names",
"exp_name += ('_e' + str(args.epochs)) if args.transfer != 0 and",
"in names_considered: train_count[name] = 0 for i in range(len(train_set[name])): img_folder",
"path in test_dir.iterdir(): if path.is_file(): continue # print(path) for fil",
"default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data in only train,",
"args.transfer != 1: exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold:",
"if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir",
"glob.glob(str(full_stylegan_dir) + '/' + name + '*') stylegan_folders = []",
"str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True,",
"plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path +",
"1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num):",
"str(train_dir) + os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, #",
"of splitting iterations in the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\",",
"'/' + name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name]",
"= 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled'",
"'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep +",
"face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer !=",
"Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close()",
"'*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] =",
"aug_img)) \"\"\" if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'}",
"str(img))) test_count[name] += 1 # addition data from stylegan if",
"{} for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/'",
"+ # '/' + verify_type + '/train/' + name +",
"in args.additional_data_dir: exp_name += '_ltr' if args.kfold != 10: exp_name",
"os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve and",
"= conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',')",
"numpy as np import matplotlib.pyplot as plt import matplotlib.colors as",
"+ str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name)",
"names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir(): if path.is_file(): continue",
"and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir",
"help=\"returns the number of splitting iterations in the cross-validator.\", default=10,",
"# '/' + verify_type + '/train/' + name + os.sep",
"both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get the additional",
"os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores)",
"type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where",
"parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data in only train, or test,",
"os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name,",
"# Compute ROC curve and ROC area for noonan fpr,",
"1: aug_num = train_count['normal'] // train_count['noonan'] - 1 for img",
"if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name) # prepare",
"for i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in",
"# ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type + '/train/' +",
"\"--additional_data_dir\", help=\"where to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ta\",",
"enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set = {} test_set =",
"if path.is_file(): continue # print(path) for fil in path.iterdir(): #",
"= argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get data\",",
"if name in orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name not in",
"+ name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if",
"remove previous data prev = glob.glob(str(train_dir) + '/*/*') for p",
"args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if",
"glob.glob(str(test_dir) + '/*/*') for p in prev: os.remove(p) # save",
"folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/'",
"train_count[name] += 1 # test for i in range(len(test_set[name])): test_count[name]",
"print(fold_idx) print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir",
"keep the dimension relative_scores = (score_np / score_sum) total_scores =",
"args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf",
"(folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep",
"mcolors import datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='for",
"os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True, args)",
"if orig_name not in names_considered: print(\"Un-considered name:\", fil.name) continue \"\"\"",
"to get the additional data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use",
"in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep + folder):",
"= img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan',",
"in test_dir.iterdir(): if path.is_file(): continue # print(path) for fil in",
"1]) for i in range(n_classes): score_sum += score_np[:, i, None]",
"#scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) # For PR curve",
"os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) #",
"verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs'",
"= 0 for i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for",
"help=\"random seed used for k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\",",
"os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/' +",
"os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] +",
"precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores)",
"img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name])) # print('copy to:',",
"the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20, type=int)",
"score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC",
"\" \"but 0 means retraining the whole network.\", default=0, type=int)",
"learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state()",
"args.additional_data_dir: exp_name += '_lag' elif 'literature' in args.additional_data_dir: exp_name +=",
"for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir),",
"import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import",
"help=\"gpu id to use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to",
"ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path,",
"+= '_lag' elif 'literature' in args.additional_data_dir: exp_name += '_ltr' if",
"network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of model used for",
"#e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir:",
"data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train)",
"= [image,] distance = learner.binfer(conf, faces, targets, args.tta) label =",
"default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\",",
"save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') #",
"train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path",
"in range(n_classes): score_sum += score_np[:, i, None] # keep the",
"os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post')",
"args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names",
"classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i in range(n_classes): score_sum",
"= tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name + '*')",
"args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder in stylegan_folders): for",
"img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img =",
"str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 # addition data",
"\"\"\" if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir",
"for noonan fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx]",
"name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type +",
"if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in",
"shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) + '/'",
"in args.stylegan_test_or_train) and (folder in stylegan_folders): # and # (folder",
"for p in prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train'",
"else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split",
"# print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name))",
"not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img in os.listdir(full_stylegan_dir + os.sep +",
"img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name,",
"parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\",",
"names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index]",
"np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number of",
"1 print(train_count, test_count) # deal with unbalanced data \"\"\" if",
"fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir)",
"use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use shuffled kfold.\",",
"data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays',",
"train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for",
"n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0],",
"ROC curve and ROC area for noonan fpr, tpr, _",
"+= 1 print(train_count, test_count) # deal with unbalanced data \"\"\"",
"parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\",",
"name + '*') if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list",
"p in prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for",
"train_count['normal'] // train_count['noonan'] > 1: aug_num = train_count['normal'] // train_count['noonan']",
"aug_img = img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir),",
"path.is_file(): continue # print(path) for fil in path.iterdir(): # print(fil)",
"+ glob.glob(str(full_stylegan_dir) + '/' + name + '*') stylegan_folders =",
"plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate')",
"os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type",
"= kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) +",
"parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get the additional data\", default=\"\", type=str)",
"= get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner",
"in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr'])",
"matplotlib.colors as mcolors import datetime if __name__ == '__main__': parser",
"test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train'",
"auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import os import",
"data prev = glob.glob(str(train_dir) + '/*/*') for p in prev:",
"'__main__': parser = argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to",
"test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr'",
"= str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep +",
"help=\"whether to use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed",
"tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name + '*') stylegan_folders",
"full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir =",
"np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr'] =",
"in range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i]) for img",
"0 img_folder = str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder +",
"img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name,",
"!= 0 and args.transfer != 1: exp_name += ('_td' +",
"+ img)) train_count[name] += 1 # test for i in",
"used for k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test",
"in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in",
"glob.glob(str(train_dir) + '/*/*') for p in prev: os.remove(p) prev =",
"only train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\",",
"glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name",
"from mtcnn import MTCNN from Learner_trans_tf import face_learner from utils",
"train_count[name] = 0 for i in range(len(train_set[name])): img_folder = str(train_set[name][i])",
"print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir",
"if args.transfer != 0 and args.transfer != 1: exp_name +=",
"default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use shuffled kfold.\", action=\"store_true\")",
"args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train,",
"args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold,",
"if 'literature' in args.additional_data_dir: data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr']",
"range(len(train_set[name])): img_folder = str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder +",
"shutil import numpy as np import matplotlib.pyplot as plt import",
"folders raw_dir = 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type",
"str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img),",
"np import matplotlib.pyplot as plt import matplotlib.colors as mcolors import",
"= {} for name in names_considered: train_count[name] = 0 for",
"Compute ROC curve and ROC area for noonan fpr, tpr,",
"data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir:",
"precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep + '/pr_{}.png'.format(exp_name))",
"parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number of splitting iterations in the",
"learner.binfer(conf, faces, targets, args.tta) label = score_names[-1] score = np.exp(distance.dot(-1))",
"= np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes =",
"os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx,",
"os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered:",
"inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner",
"For PR curve precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision",
"print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir:",
"in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index],",
"ROC area for noonan fpr, tpr, _ = roc_curve(total_names, total_scores)",
"score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for",
"datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='for face verification')",
"transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner loaded')",
"name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy')",
"os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count, test_count) # deal",
"default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data in only train,",
"score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred",
"= os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder",
"'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve and ROC",
"0 for i in range(len(train_set[name])): img_folder = str(train_set[name][i]) for img",
"score_names) score_path = os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute",
"many layer(s) used for transfer learning, \" \"but 0 means",
"for i in range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i])",
"scores = [] wrong_names = [] args.stored_result_path = args.stored_result_dir +",
"= [] wrong_names = [] args.stored_result_path = args.stored_result_dir + os.sep",
"prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for p in",
"for img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder,",
"MTCNN from Learner_trans_tf import face_learner from utils import load_facebank, draw_box_name,",
"or both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get the",
"wrong_names = [] args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19]",
"by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to use\",",
"to get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as",
"for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir),",
"os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for p in prev:",
"for img_f in add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:',",
"to use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used",
"img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep +",
"default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s) used for transfer",
"verify_type + '/train/' + name + os.sep + img)) train_count[name]",
"area for noonan fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:,",
"= np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum",
"in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data",
"init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else:",
"roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0])",
"split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\",",
"to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir),",
"distance = learner.binfer(conf, faces, targets, args.tta) label = score_names[-1] score",
"shuffle=False, random_state=None) # collect and split raw data data_dict =",
"import os import glob import shutil import numpy as np",
"aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] + '_' + str(aug_idx)",
"unbalanced data train_count = {} test_count = {} for name",
"cross-validator.\", default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\",",
"tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name +",
"for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' +",
"'_ltr' if args.kfold != 10: exp_name += ('_k' + str(args.kfold))",
"!= 20: exp_name += ('_e' + str(args.epochs)) if args.transfer !=",
"= KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None)",
"+= 1 # addition data from stylegan if 'interp' not",
"conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir,",
"= args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False,",
"img_f in add_data: if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f)",
"in range(args.kfold): train_set = {} test_set = {} for name",
"name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if args.stylegan_data_dir:",
"path.iterdir(): # print(fil) orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0]",
"import datetime if __name__ == '__main__': parser = argparse.ArgumentParser(description='for face",
"= average_precision_score(total_names, total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw",
"for name in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) \"\"\"",
"where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score",
"get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner =",
"+ os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision,",
"plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr,",
"1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05])",
"# test for i in range(len(test_set[name])): test_count[name] = 0 img_folder",
"updated') for path in test_dir.iterdir(): if path.is_file(): continue # print(path)",
"curve precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names,",
"stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if",
"name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders",
"get the additional data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional",
"1: exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name +=",
"name in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) \"\"\" if",
"(folder in stylegan_folders): # and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])):",
"args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) #",
"args.kfold != 10: exp_name += ('_k' + str(args.kfold)) if args.epochs",
"plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision))",
"= str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold,",
"random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and",
"in vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf =",
"label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np",
"import matplotlib.colors as mcolors import datetime if __name__ == '__main__':",
"stylegan data in only train, or test, or both\", default=\"\",",
"if pred != label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names",
"None] # keep the dimension relative_scores = (score_np / score_sum)",
"average_precision_score from sklearn.model_selection import KFold import os import glob import",
"in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train:",
"args.epochs) print('learner retrained.') learner.save_state() print('Model is saved') # prepare_facebank targets,",
"conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) #",
"'/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True)",
"to use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use shuffled",
"for fil in path.iterdir(): # print(fil) orig_name = ''.join([i for",
"in names_idx.keys(): if name in orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name",
"not in names_considered: print(\"Un-considered name:\", fil.name) continue \"\"\" frame =",
"help=\"use additional data in only train, or test, or both\",",
"cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf,",
"type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan data in only train, or",
"store data as np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns",
"print(exp_name) # prepare folders raw_dir = 'raw_112' verify_type = 'trans'",
"to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count = {} test_count",
"'/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores = []",
"in range(aug_num): aug_img = img[:img.rfind('.')] + '_' + str(aug_idx) +",
"conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path",
"print('learner retrained.') learner.save_state() print('Model is saved') # prepare_facebank targets, names,",
"import Path from multiprocessing import Process, Pipe,Value,Array import torch from",
"# print(path) for fil in path.iterdir(): # print(fil) orig_name =",
"'/' + name + '*') if 'innm' in args.stylegan_data_dir: tmp_list",
"= score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1])",
"test_count = {} for name in names_considered: train_count[name] = 0",
"if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf =",
"+ '*') if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list +",
"'noonan')): for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] + '_'",
"+ img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if",
"('_e' + str(args.epochs)) if args.transfer != 0 and args.transfer !=",
"# str(train_dir) + os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir,",
"stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init",
"_ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr)",
"in args.stylegan_test_or_train) and (folder in stylegan_folders): for img in os.listdir(full_stylegan_dir",
"stylegan_folders): # and # (folder not in ['noonan7','noonan19','noonan23','normal9','normal20','normal23'])): for img",
"= train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir)",
"fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' +",
"'/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready')",
"conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data",
"= os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path,",
"1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name))",
"kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False,",
"save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path =",
"args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated') for path",
"random_state=None) # collect and split raw data data_dict = {}",
"orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name not in names_considered: print(\"Un-considered name:\",",
"os import glob import shutil import numpy as np import",
"test_count[name] += 1 # addition data from stylegan if 'interp'",
"os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for",
"if train_count['normal'] // train_count['noonan'] > 1: aug_num = train_count['normal'] //",
"train_count[name] += 1 # addition data from stylegan if 'interp'",
"score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names, classes=range(n_classes))",
"arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number of splitting",
"parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used for k-fold split.\", default=6, type=int)",
"('_s' + str(args.random_seed)) print(exp_name) # prepare folders raw_dir = 'raw_112'",
"prepare folders raw_dir = 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold:",
"idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores = [] wrong_names",
"('/'.join(train_set[name][i].strip().split('/')[:-2]) + # '/' + verify_type + '/train/' + name",
"commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to use\", default=\"\",",
"parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get the additional data\", default=\"\", type=str)",
"considered, separated by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id",
"in only train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-tf\",",
"emore_dir = 'faces_emore' conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir",
"roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import os",
"and split raw data data_dict = {} idx_gen = {}",
"name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list)",
"'/*/*') for p in prev: os.remove(p) # save trains to",
"!= label: wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names)",
"Learner_trans_tf import face_learner from utils import load_facebank, draw_box_name, prepare_facebank, save_label_score,",
"print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep",
"args.additional_data_dir: exp_name += '_ltr' if args.kfold != 10: exp_name +=",
"learner.model, mtcnn, tta = args.tta) print('names_classes:', names) noonan_idx = names_idx['noonan']",
"import Process, Pipe,Value,Array import torch from config import get_config from",
"for name in names_considered: for img_f in add_data: if name",
"as np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number",
"conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir",
"folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1",
"parser.parse_args() for arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir =",
"+ os.sep + fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type",
"lw=lw, label='ROC curve (area = %0.4f)' % roc_auc) plt.plot([0, 1],",
"(train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if",
"from Learner_trans_tf import face_learner from utils import load_facebank, draw_box_name, prepare_facebank,",
"score_names = label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i",
"Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name))",
"args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name) # prepare folders",
"= data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'],",
"type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\",",
"shuffle=True, random_state=args.random_seed) else: kf = KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect",
"os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 #",
"action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used for k-fold split.\", default=6,",
"for name in names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True)",
"name, str(img))) train_count[name] += 1 # addition data from stylegan",
"id to use\", default=\"\", type=str) parser.add_argument(\"-s\", \"--use_shuffled_kfold\", help=\"whether to use",
"# print(fil) orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if",
"os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) + '/' + name,",
"len(add_data)) for name in names_considered: for img_f in add_data: if",
"conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer,",
"vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf = get_config(True,",
"curve and ROC area for noonan fpr, tpr, _ =",
"used for transfer learning, \" \"but 0 means retraining the",
"fold_idx in range(args.kfold): train_set = {} test_set = {} for",
"= glob.glob(str(test_dir) + '/*/*') for p in prev: os.remove(p) #",
"print(path) for fil in path.iterdir(): # print(fil) orig_name = ''.join([i",
"get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np",
"label = score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1)",
"and ('test' in args.stylegan_test_or_train) and (folder in stylegan_folders): # and",
"= args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path)",
"train_count['normal'] // train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')):",
"plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall,",
"in prev: os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and #",
"score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes",
"'/*/*') for p in prev: os.remove(p) prev = glob.glob(str(test_dir) +",
"score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path,",
"'*') if 'innm' in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir)",
"test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index] if 'train' in args.additional_test_or_train: train_set['noonan'] =",
"default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the number of splitting iterations",
"np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr']))",
"multiprocessing import Process, Pipe,Value,Array import torch from config import get_config",
"plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0])",
"tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*') if",
"for fold_idx in range(args.kfold): train_set = {} test_set = {}",
"import cv2 from PIL import Image import argparse from pathlib",
"\"--dataset_dir\", help=\"where to get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store",
"augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get the additional data\", default=\"\",",
"+ os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1",
"print(fil) orig_name = ''.join([i for i in fil.name.strip().split('.')[0].split('_')[0] if not",
"name in names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir)",
"print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] = np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in",
"= train_count['normal'] // train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir),",
"shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True,",
"= np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred != label:",
"+ '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = [] scores =",
"= score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path =",
"= label_binarize(score_names, classes=range(n_classes)) score_sum = np.zeros([score_np.shape[0], 1]) for i in",
"plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep +",
"exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name",
"plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average",
"learning, \" \"but 0 means retraining the whole network.\", default=0,",
"range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i]) for img in",
"face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get data\", default=\"noonan\", type=str)",
"args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan']",
"label='ROC curve (area = %0.4f)' % roc_auc) plt.plot([0, 1], [0,",
"plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}):",
"folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) +",
"img[:img.rfind('.')] + '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img),",
"print('saved!') # Compute ROC curve and ROC area for noonan",
"'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train'",
"('train' in args.stylegan_test_or_train) and (folder in stylegan_folders): for img in",
"import shutil import numpy as np import matplotlib.pyplot as plt",
"args.stylegan_test_or_train) and (folder in stylegan_folders): # and # (folder not",
"+ str(args.epochs)) if args.transfer != 0 and args.transfer != 1:",
"and args.transfer != 1: exp_name += ('_td' + str(args.transfer)) if",
"> 1: aug_num = train_count['normal'] // train_count['noonan'] - 1 for",
"img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if 'fake'",
"in names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir) +",
"print('Model is saved') # prepare_facebank targets, names, names_idx = prepare_facebank(conf,",
"train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if",
"load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve, auc,",
"if 'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr']",
"1 # test for i in range(len(test_set[name])): test_count[name] = 0",
"saved') # prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn,",
"names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta = args.tta) print('names_classes:',",
"the number of splitting iterations in the cross-validator.\", default=10, type=int)",
"shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used for k-fold",
"only train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\",",
"get_config from mtcnn import MTCNN from Learner_trans_tf import face_learner from",
"os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in",
"data data_dict = {} idx_gen = {} for name in",
"and (folder in stylegan_folders): # and # (folder not in",
"('_k' + str(args.kfold)) if args.epochs != 20: exp_name += ('_e'",
"number of splitting iterations in the cross-validator.\", default=10, type=int) parser.add_argument(\"-e\",",
"in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')]",
"encoder\", default=\"mobile\", type=str) args = parser.parse_args() for arg in vars(args):",
"image = Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf, faces,",
"os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder in",
"config import get_config from mtcnn import MTCNN from Learner_trans_tf import",
"+ folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2])",
"data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data in only",
"data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train)",
"default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get the additional data\",",
"kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random seed used for k-fold split.\",",
"10: exp_name += ('_k' + str(args.kfold)) if args.epochs != 20:",
"str(img))) test_count[name] += 1 print(train_count, test_count) # deal with unbalanced",
"# For PR curve precision, recall, _ = precision_recall_curve(total_names, total_scores)",
"'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous",
"os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi",
"+ '/' + name + '*') if 'innm' in args.stylegan_data_dir:",
"+ '/*/*') for p in prev: os.remove(p) # save trains",
"parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\",",
"os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 #",
"+ folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] +=",
"unbalanced data \"\"\" if train_count['normal'] // train_count['noonan'] > 1: aug_num",
"= 'trans' if args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir =",
"auc(fpr, tpr) # For PR curve precision, recall, _ =",
"right\") plt.savefig(args.stored_result_path + os.sep + '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure()",
"data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index], data_dict['ltr'][test_index]",
"pred = np.argmax(score, 1) if pred != label: wrong_names.append(orig_name) scores.append(score)",
"in path.iterdir(): # print(fil) orig_name = ''.join([i for i in",
"previous data prev = glob.glob(str(train_dir) + '/*/*') for p in",
"layer(s) used for transfer learning, \" \"but 0 means retraining",
"+ '/*/*') for p in prev: os.remove(p) prev = glob.glob(str(test_dir)",
"+ os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img)))",
"shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name] +=",
"i in range(len(test_set[name])): test_count[name] = 0 img_folder = str(test_set[name][i]) for",
"in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set = {} test_set",
"if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir)",
"if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if args.use_shuffled_kfold:",
"# prepare folders raw_dir = 'raw_112' verify_type = 'trans' if",
"os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir) # init kfold if",
"import load_facebank, draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve,",
"k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\", \"--tta\", help=\"whether test time augmentation\",action=\"store_true\")",
"wrong_names.append(orig_name) scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np =",
"import glob import shutil import numpy as np import matplotlib.pyplot",
"in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir),",
"parser = argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get",
"train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index,",
"'_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir =",
"addition data from stylegan if 'interp' not in data_dict.keys(): folder",
"'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and",
"lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True",
"as np import matplotlib.pyplot as plt import matplotlib.colors as mcolors",
"'/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision')",
"= 0 img_folder = str(test_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder",
"data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr'])",
"conf, inference=False, transfer=0 if args.transfer != 0: learner.load_state(conf.save_path, False, True)",
"orig_name not in names_considered: print(\"Un-considered name:\", fil.name) continue \"\"\" frame",
"\"--transfer\", help=\"how many layer(s) used for transfer learning, \" \"but",
"names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*')",
"not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])):",
"and ('train' in args.stylegan_test_or_train) and (folder in stylegan_folders): for img",
"Image.fromarray(frame) faces = [image,] distance = learner.binfer(conf, faces, targets, args.tta)",
"args = parser.parse_args() for arg in vars(args): print(arg+':', getattr(args, arg))",
"// train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for",
"total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path, wrong_names) label_path",
"{} for name in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name],",
"parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to",
"if 'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test'",
"str(args.epochs)) if args.transfer != 0 and args.transfer != 1: exp_name",
"test_set['ltr'])) # remove previous data prev = glob.glob(str(train_dir) + '/*/*')",
"in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and ('train' in",
"if name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:',",
"+ '/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/' + name,",
"img in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)),",
"data_dict['ltr'] = np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names =",
"'wrong_names.npy') save_label_score(name_path, wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path",
"0 means retraining the whole network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\",",
"plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0,",
"plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0,",
"glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name + '*') if 'innm' in",
"= np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev = glob.glob(str(train_dir)",
"# collect and split raw data data_dict = {} idx_gen",
"+ name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)) data_dict[name] =",
"!= 0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner",
"test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index)",
"default=10, type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\",",
"+ verify_type + '/train/' + name + os.sep + img))",
"in os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name, str(img)))",
"prev = glob.glob(str(train_dir) + '/*/*') for p in prev: os.remove(p)",
"as plt import matplotlib.colors as mcolors import datetime if __name__",
"name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name",
"is saved') # prepare_facebank targets, names, names_idx = prepare_facebank(conf, learner.model,",
"= np.array(tmp_list) idx_gen[name] = kf.split(data_dict[name]) if 'literature' in args.additional_data_dir: data_dict['ltr']",
"'train' in args.additional_test_or_train: train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in",
"np.argmax(score, 1) if pred != label: wrong_names.append(orig_name) scores.append(score) score_names =",
"from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score from sklearn.model_selection import",
"save trains to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' #",
"in prev: os.remove(p) prev = glob.glob(str(test_dir) + '/*/*') for p",
"data as np arrays', default=\"results/trans/\", type=str) parser.add_argument(\"-k\", \"--kfold\", help=\"returns the",
"= face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer",
"test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if",
"fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc =",
"wrong_names) label_path = os.path.join(args.stored_result_path, 'labels_trans.npy') save_label_score(label_path, score_names) score_path = os.path.join(args.stored_result_path,",
"{} test_count = {} for name in names_considered: train_count[name] =",
"+ str(args.kfold)) if args.epochs != 20: exp_name += ('_e' +",
"+ '/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g. smile_refine_mtcnn_112_divi full_stylegan_dir",
"args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev",
"test_set = {} for name in names_considered: (train_index, test_index) =",
"+ fake_dict[name])) # print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/'",
"additional data in only train, or test, or both\", default=\"\",",
"plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0,",
"if not i.isdigit()]) for name in names_idx.keys(): if name in",
"score_sum += score_np[:, i, None] # keep the dimension relative_scores",
"import torch from config import get_config from mtcnn import MTCNN",
"average_precision_score(total_names, total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw =",
"fil in path.iterdir(): # print(fil) orig_name = ''.join([i for i",
"+= 1 # test for i in range(len(test_set[name])): test_count[name] =",
"= precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) # plots plt.figure()",
"argparse from pathlib import Path from multiprocessing import Process, Pipe,Value,Array",
"# print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) +",
"default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays', default=\"results/trans/\",",
"\"--random_seed\", help=\"random seed used for k-fold split.\", default=6, type=int) parser.add_argument(\"-tta\",",
"the whole network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of model",
"and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced data train_count",
"name, str(img))) test_count[name] += 1 # addition data from stylegan",
"os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if 'fake' in args.additional_data_dir: fake_dict =",
"with unbalanced data \"\"\" if train_count['normal'] // train_count['noonan'] > 1:",
"# remove previous data prev = glob.glob(str(train_dir) + '/*/*') for",
"names_considered: train_count[name] = 0 for i in range(len(train_set[name])): img_folder =",
"img_folder = str(train_set[name][i]) for img in os.listdir(img_folder): shutil.copy(img_folder + os.sep",
"in os.listdir(full_stylegan_dir + os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir),",
"= glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data)) for",
"in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), #",
"for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in range(aug_num): aug_img",
"!= 10: exp_name += ('_k' + str(args.kfold)) if args.epochs !=",
"lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area",
"in orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name not in names_considered: print(\"Un-considered",
"precision_recall_curve, average_precision_score from sklearn.model_selection import KFold import os import glob",
"\"--stylegan_test_or_train\", help=\"use stylegan data in only train, or test, or",
"if args.stylegan_data_dir and ('train' in args.stylegan_test_or_train) and (folder in stylegan_folders):",
"MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if",
"os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name]",
"average_precision = average_precision_score(total_names, total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS)",
"import get_config from mtcnn import MTCNN from Learner_trans_tf import face_learner",
"conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf,",
"str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for fold_idx, (train_index, test_index)",
"args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir:",
"score_names.append(names_idx[name]) \"\"\" if orig_name not in names_considered: print(\"Un-considered name:\", fil.name)",
"os.remove(p) # save trains to conf.facebank_path/args.dataset_dir/'train' and # tests to",
"parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s) used for transfer learning, \"",
"for i in fil.name.strip().split('.')[0].split('_')[0] if not i.isdigit()]) for name in",
"\"\"\" if orig_name not in names_considered: print(\"Un-considered name:\", fil.name) continue",
"print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name])) #",
"= str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir = str(conf.data_path/'facebank'/args.additional_data_dir)",
"total_scores) average_precision = average_precision_score(total_names, total_scores) # plots plt.figure() colors =",
"relative_scores) print('saved!') # Compute ROC curve and ROC area for",
"folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and",
"\"--use_shuffled_kfold\", help=\"whether to use shuffled kfold.\", action=\"store_true\") parser.add_argument(\"-rs\", \"--random_seed\", help=\"random",
"= np.argmax(score, 1) if pred != label: wrong_names.append(orig_name) scores.append(score) score_names",
"KFold(n_splits=args.kfold, shuffle=False, random_state=None) # collect and split raw data data_dict",
"os.listdir(img_folder): shutil.copy(img_folder + os.sep + str(img), os.path.join(str(test_dir), name, str(img))) test_count[name]",
"= {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data = glob.glob(str(full_additional_dir) +",
"tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr,",
"range(n_classes): score_sum += score_np[:, i, None] # keep the dimension",
"Pipe,Value,Array import torch from config import get_config from mtcnn import",
"means retraining the whole network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types",
"+ '/' + name + '*') stylegan_folders = [] print(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir))",
"deal with unbalanced data \"\"\" if train_count['normal'] // train_count['noonan'] >",
"precision_recall_curve(total_names, total_scores) average_precision = average_precision_score(total_names, total_scores) # plots plt.figure() colors",
"exist_ok=True) os.makedirs(str(test_dir) + '/' + name, exist_ok=True) if args.stylegan_data_dir: #e.g.",
"= {} for name in names_considered: (train_index, test_index) = next(idx_gen[name])",
"KFold import os import glob import shutil import numpy as",
"in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir) + '/' + name +",
"time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get the additional data\",",
"shutil.copy(img_folder + os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] +=",
"test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold): train_set = {}",
"'interp' not in data_dict.keys(): folder = os.path.basename(train_set[name][i]) if args.stylegan_data_dir and",
"test for i in range(len(test_set[name])): test_count[name] = 0 img_folder =",
"for different types considered, separated by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\",",
"fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train = get_config(True, args) conf_train.emore_folder",
"plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path + os.sep +",
"argparse.ArgumentParser(description='for face verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get data\", default=\"noonan\",",
"import KFold import os import glob import shutil import numpy",
"elif 'literature' in args.additional_data_dir: exp_name += '_ltr' if args.kfold !=",
"type=str) parser.add_argument('-sd','--stored_result_dir',help='where to store data as np arrays', default=\"results/trans/\", type=str)",
"kfold if args.use_shuffled_kfold: kf = KFold(n_splits=args.kfold, shuffle=True, random_state=args.random_seed) else: kf",
"args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/' + name",
"{} test_set = {} for name in names_considered: (train_index, test_index)",
"if 'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir",
"args.transfer != 0: learner.load_state(conf.save_path, False, True) print('learner loaded') learner.train(conf_train, args.epochs)",
"// train_count['noonan'] > 1: aug_num = train_count['normal'] // train_count['noonan'] -",
"frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces = [image,] distance",
"relative_scores = (score_np / score_sum) total_scores = relative_scores.ravel() total_names =",
"= np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names =",
"args.stylegan_test_or_train) and (folder in stylegan_folders): for img in os.listdir(full_stylegan_dir +",
"idx_gen = {} for name in names_considered: tmp_list = glob.glob(str(conf.data_path/'facebank'/args.dataset_dir/raw_dir)",
"\"--arch\", help=\"types of model used for encoder\", default=\"mobile\", type=str) args",
"next(idx_gen[name]) train_set[name], test_set[name] = data_dict[name][train_index], data_dict[name][test_index] if 'ltr' in data_dict.keys():",
"for aug_idx in range(aug_num): aug_img = img[:img.rfind('.')] + '_' +",
"= get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn = MTCNN() print('mtcnn",
"= np.array(glob.glob(str(full_additional_dir) + '/*')) idx_gen['ltr'] = kf.split(data_dict['ltr']) score_names = []",
"+ '_' + str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir),",
"to:', img_f.replace(str(full_additional_dir), # str(train_dir) + os.sep + fake_dict[name])) # print('copy",
"import MTCNN from Learner_trans_tf import face_learner from utils import load_facebank,",
"roc_auc = auc(fpr, tpr) # For PR curve precision, recall,",
"0 and args.transfer != 1: exp_name += ('_td' + str(args.transfer))",
"if args.epochs != 20: exp_name += ('_e' + str(args.epochs)) if",
"= os.path.join(args.stored_result_path, 'scores_trans.npy') save_label_score(score_path, relative_scores) print('saved!') # Compute ROC curve",
"1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name, average_precision)) plt.savefig(args.stored_result_path + os.sep",
"exp_name += '_lag' elif 'literature' in args.additional_data_dir: exp_name += '_ltr'",
"draw_box_name, prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve,",
"exp_name += ('_k' + str(args.kfold)) if args.epochs != 20: exp_name",
"print('facebank updated') for path in test_dir.iterdir(): if path.is_file(): continue #",
"and (folder in stylegan_folders): for img in os.listdir(full_stylegan_dir + os.sep",
"Image import argparse from pathlib import Path from multiprocessing import",
"str(args.random_seed)) print(exp_name) # prepare folders raw_dir = 'raw_112' verify_type =",
"# train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir = conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test'",
"if 'test' in args.additional_test_or_train: test_set['noonan'] = np.concatenate((test_set['noonan'], test_set['ltr'])) # remove",
"names_considered = args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG'",
"+ os.sep + str(datetime.datetime.now())[:19] if not os.path.exists(args.stored_result_path): os.mkdir(args.stored_result_path) # for",
"from multiprocessing import Process, Pipe,Value,Array import torch from config import",
"default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of model used for encoder\",",
"arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore' conf",
"train_count['noonan'] > 1: aug_num = train_count['normal'] // train_count['noonan'] - 1",
"+ name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets ready') conf_train",
"os.sep + img)) train_count[name] += 1 # test for i",
"precision, where='post') plt.xlabel('Recall') plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision",
"False, True) print('learner loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model",
"if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir)",
"'faces_emore' conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn =",
"print('names_classes:', names) noonan_idx = names_idx['noonan'] print('facebank updated') for path in",
"= [] args.stored_result_path = args.stored_result_dir + os.sep + str(datetime.datetime.now())[:19] if",
"not in data_dict.keys(): folder = os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test'",
"PIL import Image import argparse from pathlib import Path from",
"test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get the additional",
"if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name",
"for arg in vars(args): print(arg+':', getattr(args, arg)) emore_dir = 'faces_emore'",
"os.path.join(str(train_dir), name, str(img))) train_count[name] += 1 # addition data from",
"separated by commas\", default=\"normal,noonan,others\", type=str) parser.add_argument(\"-g\", \"--gpu_id\", help=\"gpu id to",
"conf.emore_folder/'imgs' test_dir = conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir)",
"os.path.basename(test_set[name][i]) if args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder in",
"total_scores) #scores_np[:, noonan_idx] roc_auc = auc(fpr, tpr) # For PR",
"the dimension relative_scores = (score_np / score_sum) total_scores = relative_scores.ravel()",
"args.use_shuffled_kfold: verify_type += '_shuffled' # train_dir = conf.facebank_path/args.dataset_dir/verify_type/'train' train_dir =",
"'_lag' elif 'literature' in args.additional_data_dir: exp_name += '_ltr' if args.kfold",
"args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir = conf.data_path/'facebank'/'noonan+normal'/args.additional_data_dir add_data =",
"score = np.exp(distance.dot(-1)) pred = np.argmax(score, 1) if pred !=",
"'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img)) \"\"\" if 'fake' in args.additional_data_dir:",
"print('copy to:', img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name)) shutil.copy(img_f,",
"train_set['noonan'] = np.concatenate((train_set['noonan'], train_set['ltr'])) if 'test' in args.additional_test_or_train: test_set['noonan'] =",
"help=\"whether test time augmentation\",action=\"store_true\") parser.add_argument(\"-a\", \"--additional_data_dir\", help=\"where to get the",
"if 'LAG' in args.additional_data_dir: exp_name += '_lag' elif 'literature' in",
"name in orig_name: score_names.append(names_idx[name]) \"\"\" if orig_name not in names_considered:",
"\"--kfold\", help=\"returns the number of splitting iterations in the cross-validator.\",",
"+ '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name], os.path.basename(img_f))) print(fold_idx) print('datasets",
"= conf.data_path/emore_dir conf_train.stored_result_dir = args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx))",
"collect and split raw data data_dict = {} idx_gen =",
"data_dict[name][test_index] if 'ltr' in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'],",
"i, None] # keep the dimension relative_scores = (score_np /",
"in args.additional_data_dir: exp_name += '_lag' elif 'literature' in args.additional_data_dir: exp_name",
"type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names for different types considered, separated by",
"targets, names, names_idx = prepare_facebank(conf, learner.model, mtcnn, tta = args.tta)",
"= relative_scores.ravel() total_names = score_names.ravel() name_path = os.path.join(args.stored_result_path, 'wrong_names.npy') save_label_score(name_path,",
"help=\"types of model used for encoder\", default=\"mobile\", type=str) args =",
"data train_count = {} test_count = {} for name in",
"as mcolors import datetime if __name__ == '__main__': parser =",
"of model used for encoder\", default=\"mobile\", type=str) args = parser.parse_args()",
"[image,] distance = learner.binfer(conf, faces, targets, args.tta) label = score_names[-1]",
"np.array(wrong_names) score_np = np.squeeze(np.array(scores)) n_classes = score_np.shape[1] score_names = label_binarize(score_names,",
"trains to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count",
"scores.append(score) score_names = np.array(score_names) wrong_names = np.array(wrong_names) score_np = np.squeeze(np.array(scores))",
"= 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC curve (area =",
"= list(mcolors.TABLEAU_COLORS) lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw, label='ROC",
"names_considered: os.makedirs(str(train_dir) + '/' + name, exist_ok=True) os.makedirs(str(test_dir) + '/'",
"- 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx in",
"name:\", fil.name) continue \"\"\" frame = cv2.imread(str(fil)) image = Image.fromarray(frame)",
"'*.png') print('additional:', args.additional_data_dir, len(add_data)) for name in names_considered: for img_f",
"= args.names_considered.strip().split(',') exp_name = args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in",
"the additional data\", default=\"\", type=str) parser.add_argument(\"-ta\", \"--additional_test_or_train\", help=\"use additional data",
"+ str(args.random_seed)) print(exp_name) # prepare folders raw_dir = 'raw_112' verify_type",
"1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive",
"learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if",
"for fold_idx, (train_index, test_index) in enumerate(kf.split(data_dict[names_considered[0]])): for fold_idx in range(args.kfold):",
"= 'faces_emore' conf = get_config(True, args) conf.emore_folder = conf.data_path/emore_dir mtcnn",
"in data_dict.keys(): (train_index, test_index) = next(idx_gen['ltr']) train_set['ltr'], test_set['ltr'] = data_dict['ltr'][train_index],",
"total_scores) # plots plt.figure() colors = list(mcolors.TABLEAU_COLORS) lw = 2",
"= names_idx['noonan'] print('facebank updated') for path in test_dir.iterdir(): if path.is_file():",
"+= ('_e' + str(args.epochs)) if args.transfer != 0 and args.transfer",
"train_count = {} test_count = {} for name in names_considered:",
"transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0 if args.transfer != 0:",
"'LAG' in args.additional_data_dir: exp_name += '_lag' elif 'literature' in args.additional_data_dir:",
"for transfer learning, \" \"but 0 means retraining the whole",
"if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name += '_lag' elif",
"args.stylegan_data_dir and ('test' in args.stylegan_test_or_train) and (folder in stylegan_folders): #",
"add_data = glob.glob(str(full_additional_dir) + os.sep + '*.png') print('additional:', args.additional_data_dir, len(add_data))",
"+ str(aug_idx) + img[img.rfind('.'):] shutil.copy(os.path.join(str(train_dir), 'noonan', img), os.path.join(str(train_dir), 'noonan', aug_img))",
"= glob.glob(str(train_dir) + '/*/*') for p in prev: os.remove(p) prev",
"noonan_idx] roc_auc = auc(fpr, tpr) # For PR curve precision,",
"conf.emore_folder/'test' conf.facebank_path = train_dir if os.path.exists(train_dir): shutil.rmtree(train_dir) if os.path.exists(test_dir): shutil.rmtree(test_dir)",
"/ score_sum) total_scores = relative_scores.ravel() total_names = score_names.ravel() name_path =",
"plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path",
"+ '/fp_tp_{}.png'.format(exp_name)) plt.close() # plt.show() plt.figure() plt.step(recall, precision, where='post') plt.xlabel('Recall')",
"noonan fpr, tpr, _ = roc_curve(total_names, total_scores) #scores_np[:, noonan_idx] roc_auc",
"plt.ylabel('Precision') plt.ylim([0.0, 1.05]) plt.xlim([0.0, 1.0]) plt.title('Average precision score ({}): AP={:0.4f}'.format(exp_name,",
"data_dict = {} idx_gen = {} for name in names_considered:",
"folder, str(img)), os.path.join(str(test_dir), name, str(img))) test_count[name] += 1 print(train_count, test_count)",
"from stylegan if 'interp' not in data_dict.keys(): folder = os.path.basename(test_set[name][i])",
"raw_dir = 'raw_112' verify_type = 'trans' if args.use_shuffled_kfold: verify_type +=",
"continue \"\"\" frame = cv2.imread(str(fil)) image = Image.fromarray(frame) faces =",
"retraining the whole network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of",
"train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how",
"+= ('_k' + str(args.kfold)) if args.epochs != 20: exp_name +=",
"'literature' in args.additional_data_dir: exp_name += '_ltr' if args.kfold != 10:",
"in args.stylegan_data_dir: tmp_list = tmp_list + glob.glob(str(full_stylegan_dir) + '/' +",
"np.concatenate((test_set['noonan'], test_set['ltr'])) # remove previous data prev = glob.glob(str(train_dir) +",
"str(args.transfer)) if args.use_shuffled_kfold: exp_name += ('_s' + str(args.random_seed)) print(exp_name) #",
"train_count['noonan'] - 1 for img in os.listdir(os.path.join(str(train_dir), 'noonan')): for aug_idx",
"PR curve precision, recall, _ = precision_recall_curve(total_names, total_scores) average_precision =",
"img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir), # str(train_dir)",
"whole network.\", default=0, type=int) parser.add_argument(\"-ac\", \"--arch\", help=\"types of model used",
"args.dataset_dir[:4] if args.additional_data_dir: if 'LAG' in args.additional_data_dir: exp_name += '_lag'",
"'/train/' + name + os.sep + img)) train_count[name] += 1",
"mtcnn = MTCNN() print('mtcnn loaded') names_considered = args.names_considered.strip().split(',') exp_name =",
"train, or test, or both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where",
"\"--names_considered\", help=\"names for different types considered, separated by commas\", default=\"normal,noonan,others\",",
"get the additional data\", default=\"\", type=str) parser.add_argument(\"-ts\", \"--stylegan_test_or_train\", help=\"use stylegan",
"+ os.sep + str(img), os.path.join(str(train_dir), name, str(img))) train_count[name] += 1",
"if 'fake' in args.additional_data_dir: fake_dict = {'noonan':'normal', 'normal':'noonan'} full_additional_dir =",
"in names_considered: for img_f in add_data: if name in img_f.strip().split(os.sep)[-1]:",
"% roc_auc) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0,",
"plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower",
"args.tta) label = score_names[-1] score = np.exp(distance.dot(-1)) pred = np.argmax(score,",
"# count unbalanced data train_count = {} test_count = {}",
"+ os.sep + folder): shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(test_dir), name, str(img)))",
"= learner.binfer(conf, faces, targets, args.tta) label = score_names[-1] score =",
"score_names = [] scores = [] wrong_names = [] args.stored_result_path",
"str(img))) train_count[name] += 1 # addition data from stylegan if",
"Path from multiprocessing import Process, Pipe,Value,Array import torch from config",
"verification') parser.add_argument(\"-ds\", \"--dataset_dir\", help=\"where to get data\", default=\"noonan\", type=str) parser.add_argument('-sd','--stored_result_dir',help='where",
"+ name + os.sep + img)) train_count[name] += 1 #",
"'/' + verify_type + '/train/' + name + os.sep +",
"('test' in args.stylegan_test_or_train) and (folder in stylegan_folders): # and #",
"args.stored_result_path learner = face_learner(conf=conf_train, transfer=args.transfer, ext=exp_name+'_'+str(fold_idx)) # conf, inference=False, transfer=0",
"for name in names_considered: (train_index, test_index) = next(idx_gen[name]) train_set[name], test_set[name]",
"ready') conf_train = get_config(True, args) conf_train.emore_folder = conf.data_path/emore_dir conf_train.stored_result_dir =",
"os.path.exists(test_dir): shutil.rmtree(test_dir) os.mkdir(train_dir) os.mkdir(test_dir) for name in names_considered: os.makedirs(str(train_dir) +",
"i in range(n_classes): score_sum += score_np[:, i, None] # keep",
"Positive Rate') plt.ylabel('True Positive Rate') plt.title('ROC_{}'.format(exp_name)) plt.legend(loc=\"lower right\") plt.savefig(args.stored_result_path +",
"smile_refine_mtcnn_112_divi full_stylegan_dir = str(conf.data_path/'facebank'/'stylegan'/args.stylegan_data_dir) stylegan_folders = os.listdir(full_stylegan_dir) if args.additional_data_dir: full_additional_dir",
"test, or both\", default=\"\", type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get",
"or both\", default=\"\", type=str) parser.add_argument(\"-tf\", \"--transfer\", help=\"how many layer(s) used",
"!= 1: exp_name += ('_td' + str(args.transfer)) if args.use_shuffled_kfold: exp_name",
"shutil.copy(os.path.join(full_stylegan_dir, folder, str(img)), os.path.join(str(train_dir), name, str(img))) # ('/'.join(train_set[name][i].strip().split('/')[:-2]) + #",
"loaded') learner.train(conf_train, args.epochs) print('learner retrained.') learner.save_state() print('Model is saved') #",
"from PIL import Image import argparse from pathlib import Path",
"for name in names_considered: train_count[name] = 0 for i in",
"img_f.replace(args.additional_data_dir, # verify_type + '/train/' + name)) shutil.copy(img_f, os.path.join(str(train_dir), fake_dict[name],",
"type=str) parser.add_argument(\"-as\", \"--stylegan_data_dir\", help=\"where to get the additional data\", default=\"\",",
"transfer learning, \" \"but 0 means retraining the whole network.\",",
"name in img_f.strip().split(os.sep)[-1]: # print('source:', img_f) # print('copy to:', img_f.replace(str(full_additional_dir),",
"train_set = {} test_set = {} for name in names_considered:",
"to conf.facebank_path/args.dataset_dir/'train' and # tests to conf.data_path/'facebank'/args.dataset_dir/'test' # count unbalanced",
"type=int) parser.add_argument(\"-e\", \"--epochs\", help=\"training epochs\", default=20, type=int) parser.add_argument(\"-n\", \"--names_considered\", help=\"names",
"\"--additional_test_or_train\", help=\"use additional data in only train, or test, or",
"prepare_facebank, save_label_score, label_binarize from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score",
"getattr(args, arg)) emore_dir = 'faces_emore' conf = get_config(True, args) conf.emore_folder"
] |
[
"for your reply. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait",
"def metod2(cls, value, val2=\"\"): cls.value = 2 print(f\"\\t>>> metod 2,",
"print(\"Run the method and give us the response reading code",
"on returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg)",
"time.sleep(.5) print(\"Returned metod 1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this",
"print(\"Trying metod 2, called and returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False))",
"dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by code only :\", dr_cls.dr_code(code2, wait=1))",
"self.value @classmethod def metod2(cls, value, val2=\"\"): cls.value = 2 print(f\"\\t>>>",
"reply. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until the",
"metod 3, add: {value}, now value : {TryClass.value}, val2: {val2}\")",
"data in the reading code? : dr_code=43534\") while not dr_cls.metod1(dr_code=code1):",
"dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until the reply comes. metod 1",
"dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec for your reply. metod 1",
"\"KwArG\"})) while True: # dr_cls.dr_binds_check() print(\"Run the method and give",
"= 1 valu = 2 val = 3 va =",
"data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this way give the last",
"1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this way give the",
"cls.value @staticmethod def metod3(value, val2=\"\"): TryClass.value += value print(f\"\\t>>> metod",
":\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod",
"= 2 val = 3 va = 4 v =",
"print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if __name__ == \"__main__\": try: from",
"while True: # dr_cls.dr_binds_check() print(\"Run the method and give us",
"def metod1(self, value, val2=\"\"): self.value += value print(f\"\\t>>> metod 1,",
"dr_code=True) print(\"Search by code only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod",
"import time class TryClass: value = 1 valu = 2",
"valu = 2 val = 3 va = 4 v",
"reading code : dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is",
"until the reply comes. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1))",
"while not dr_cls.metod1(dr_code=code1): print(\"We are waiting for the data with",
"= 5 def __init__(self, value=4): print(\"Created TryClass :\", self) self.value",
"kwargs={}, worker=False) print(\"Starting values :\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1",
"print(\"Returned metod 1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this way",
"dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2, called and returned :\", dr_cls.metod2(10,",
"print(\"Wait until the reply comes. metod 1 :\", dr_cls.metod1(5, val2=\"1\",",
"1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until the reply comes.",
"last return value : nothing or dr_code=False\") code2 = dr_cls.metod2(10,",
"add: {value}, now value : {TryClass.value}, val2: {val2}\") return TryClass.value",
"kwargs={\"kwarg\": \"KwArG\"})) while True: # dr_cls.dr_binds_check() print(\"Run the method and",
"via bind to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\":",
"give the last return value : nothing or dr_code=False\") code2",
"Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if __name__ == \"__main__\":",
"3, called and returned :\", dr_cls.metod3(15, val2=\"3\")) print(\"\\n\"*2) time.sleep(3) dr_cls.dr_terminate()",
"def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this metod, on returned result\"\"\"",
"not dr_cls.metod1(dr_code=code1): print(\"We are waiting for the data with this",
"only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2, called and returned",
"dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while True: #",
"= dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there data in the reading",
": {cls.value}, val2: {val2}\") return cls.value @staticmethod def metod3(value, val2=\"\"):",
"in the reading code? : dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We",
"the method and give us the response reading code :",
"code :\", code1) time.sleep(.5) print(\"Returned metod 1 data :\", dr_cls.metod1(dr_code=code1))",
"dr_wait=1)) print(\"Wait until the reply comes. metod 1 :\", dr_cls.metod1(5,",
"def metod3(value, val2=\"\"): TryClass.value += value print(f\"\\t>>> metod 3, add:",
"dr_code=True) print(\"Metod 1, call, via bind to func\", dr_cls.dr_bind(code0, event_call,",
"metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\",",
"add: {value}, now value : {cls.value}, val2: {val2}\") return cls.value",
"dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there data in the reading code?",
"code? : dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We are waiting for",
"kwarg) if __name__ == \"__main__\": try: from dirio import Dirio",
"dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1,",
"+= value print(f\"\\t>>> metod 1, add: {value}, now value :",
"{TryClass.value}, val2: {val2}\") return TryClass.value def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call",
"metod 1, add: {value}, now value : {self.value}, val2: {val2}\")",
"{cls.value}, val2: {val2}\") return cls.value @staticmethod def metod3(value, val2=\"\"): TryClass.value",
"metod 3, called and returned :\", dr_cls.metod3(15, val2=\"3\")) print(\"\\n\"*2) time.sleep(3)",
"val2=\"\"): TryClass.value += value print(f\"\\t>>> metod 3, add: {value}, now",
"print(f\"\\t>>> metod 2, add: {value}, now value : {cls.value}, val2:",
"by code only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2, called",
"returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if",
"code only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2, called and",
"metod2(cls, value, val2=\"\"): cls.value = 2 print(f\"\\t>>> metod 2, add:",
"3, add: {value}, now value : {TryClass.value}, val2: {val2}\") return",
"dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1, call, via bind to func\",",
"aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while True: # dr_cls.dr_binds_check() print(\"Run the",
"dr_cls.dr_binds_check() print(\"Run the method and give us the response reading",
"\"__main__\": try: from dirio import Dirio except: from ..dirio import",
"called and returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod 3,",
"{val2}\") return TryClass.value def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this metod,",
"dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod 3, called and returned :\",",
"value print(f\"\\t>>> metod 1, add: {value}, now value : {self.value},",
"value=4): print(\"Created TryClass :\", self) self.value = value def metod1(self,",
":\", self) self.value = value def metod1(self, value, val2=\"\"): self.value",
"called this way give the last return value : nothing",
"waiting for the data with this code :\", code1) time.sleep(.5)",
"sec for your reply. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1))",
"= value def metod1(self, value, val2=\"\"): self.value += value print(f\"\\t>>>",
"time.sleep(2) return self.value @classmethod def metod2(cls, value, val2=\"\"): cls.value =",
"are waiting for the data with this code :\", code1)",
"now value : {cls.value}, val2: {val2}\") return cls.value @staticmethod def",
"value : {cls.value}, val2: {val2}\") return cls.value @staticmethod def metod3(value,",
"5 def __init__(self, value=4): print(\"Created TryClass :\", self) self.value =",
"value : {TryClass.value}, val2: {val2}\") return TryClass.value def event_call(other_arg, kwarg=\"-\",",
"this way give the last return value : nothing or",
"print(\"Starting values :\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec for",
"class TryClass: value = 1 valu = 2 val =",
"TryClass: value = 1 valu = 2 val = 3",
"= Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting values :\", dr_cls.value, dr_cls)",
":\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec for your reply.",
"val2=\"\"): cls.value = 2 print(f\"\\t>>> metod 2, add: {value}, now",
"self) self.value = value def metod1(self, value, val2=\"\"): self.value +=",
"the reading code? : dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We are",
": dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We are waiting for the",
"this code :\", code1) time.sleep(.5) print(\"Returned metod 1 data :\",",
"the reply comes. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0",
"1, call, via bind to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\",",
"= dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1, call, via bind to",
"dr_code=True) print(\"Is there data in the reading code? : dr_code=43534\")",
": nothing or dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search",
"except: from ..dirio import Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={},",
"2, called and returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod",
"{value}, now value : {cls.value}, val2: {val2}\") return cls.value @staticmethod",
"returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod 3, called and",
"print(\"Wait 1 sec for your reply. metod 1 :\", dr_cls.metod1(5,",
"value = 1 valu = 2 val = 3 va",
"print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if __name__ ==",
"args=(888,), kwargs={}, worker=False) print(\"Starting values :\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait",
"func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while True:",
"and returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod 3, called",
"val = 3 va = 4 v = 5 def",
"self.value = value def metod1(self, value, val2=\"\"): self.value += value",
"kwarg=\"-\", result=None): \"\"\"Call this metod, on returned result\"\"\" print(f\"Bind Result,",
"val2=\"1\", dr_code=True) print(\"Is there data in the reading code? :",
"3 va = 4 v = 5 def __init__(self, value=4):",
"dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec for your reply. metod",
"return value : nothing or dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\",",
"v = 5 def __init__(self, value=4): print(\"Created TryClass :\", self)",
"= dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by code only :\", dr_cls.dr_code(code2,",
"dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We are waiting for the data",
"True: # dr_cls.dr_binds_check() print(\"Run the method and give us the",
"import Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting values",
"response reading code : dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True)",
":\", code1) time.sleep(.5) print(\"Returned metod 1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods",
"metod, on returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\",",
"2 val = 3 va = 4 v = 5",
"event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this metod, on returned result\"\"\" print(f\"Bind",
"data with this code :\", code1) time.sleep(.5) print(\"Returned metod 1",
"now value : {self.value}, val2: {val2}\") time.sleep(2) return self.value @classmethod",
"@staticmethod def metod3(value, val2=\"\"): TryClass.value += value print(f\"\\t>>> metod 3,",
"{val2}\") return cls.value @staticmethod def metod3(value, val2=\"\"): TryClass.value += value",
"Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting values :\", dr_cls.value, dr_cls) print(\"\\n\"*2)",
"method and give us the response reading code : dr_code=True\")",
"for the data with this code :\", code1) time.sleep(.5) print(\"Returned",
"the last return value : nothing or dr_code=False\") code2 =",
"TryClass.value += value print(f\"\\t>>> metod 3, add: {value}, now value",
"value : {self.value}, val2: {val2}\") time.sleep(2) return self.value @classmethod def",
"<gh_stars>0 import time class TryClass: value = 1 valu =",
"return TryClass.value def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this metod, on",
"from ..dirio import Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False)",
"give us the response reading code : dr_code=True\") code1 =",
"with this code :\", code1) time.sleep(.5) print(\"Returned metod 1 data",
"{result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if __name__ == \"__main__\": try:",
"or dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by code",
"and give us the response reading code : dr_code=True\") code1",
"code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by code only :\",",
"1 sec for your reply. metod 1 :\", dr_cls.metod1(5, val2=\"1\",",
"# dr_cls.dr_binds_check() print(\"Run the method and give us the response",
"dr_cls.metod1(dr_code=code1)) print(\"Methods called this way give the last return value",
"the data with this code :\", code1) time.sleep(.5) print(\"Returned metod",
"__init__(self, value=4): print(\"Created TryClass :\", self) self.value = value def",
"value : nothing or dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True)",
"metod 2, called and returned :\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying",
"dr_code=False)) print(\"Trying metod 3, called and returned :\", dr_cls.metod3(15, val2=\"3\"))",
"now value : {TryClass.value}, val2: {val2}\") return TryClass.value def event_call(other_arg,",
"\"\"\"Call this metod, on returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\",",
"call, via bind to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ),",
"print(\"\\n\"*2) print(\"Wait 1 sec for your reply. metod 1 :\",",
"Dirio except: from ..dirio import Dirio dr_cls = Dirio(target=TryClass, args=(888,),",
"other_arg) print(\"kwarg\", kwarg) if __name__ == \"__main__\": try: from dirio",
"Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting values :\",",
"1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True)",
"args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while True: # dr_cls.dr_binds_check() print(\"Run",
"time class TryClass: value = 1 valu = 2 val",
"from dirio import Dirio except: from ..dirio import Dirio dr_cls",
"dr_cls.metod1(dr_code=code1): print(\"We are waiting for the data with this code",
"wait=1)) print(\"Trying metod 2, called and returned :\", dr_cls.metod2(10, val2=\"2\",",
"cls.value = 2 print(f\"\\t>>> metod 2, add: {value}, now value",
"import Dirio except: from ..dirio import Dirio dr_cls = Dirio(target=TryClass,",
"reply comes. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 =",
"), kwargs={\"kwarg\": \"KwArG\"})) while True: # dr_cls.dr_binds_check() print(\"Run the method",
":\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until the reply comes. metod",
"bind to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"}))",
"va = 4 v = 5 def __init__(self, value=4): print(\"Created",
"the response reading code : dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\",",
"metod3(value, val2=\"\"): TryClass.value += value print(f\"\\t>>> metod 3, add: {value},",
": dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there data",
"val2=\"\"): self.value += value print(f\"\\t>>> metod 1, add: {value}, now",
"val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1, call,",
"code1) time.sleep(.5) print(\"Returned metod 1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called",
"values :\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec for your",
"add: {value}, now value : {self.value}, val2: {val2}\") time.sleep(2) return",
"value def metod1(self, value, val2=\"\"): self.value += value print(f\"\\t>>> metod",
"this metod, on returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg)",
"metod 1 data :\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this way give",
"try: from dirio import Dirio except: from ..dirio import Dirio",
"..dirio import Dirio dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting",
"us the response reading code : dr_code=True\") code1 = dr_cls.metod1(5,",
"1, add: {value}, now value : {self.value}, val2: {val2}\") time.sleep(2)",
"to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while",
"val2: {val2}\") time.sleep(2) return self.value @classmethod def metod2(cls, value, val2=\"\"):",
"value print(f\"\\t>>> metod 3, add: {value}, now value : {TryClass.value},",
"val2: {val2}\") return cls.value @staticmethod def metod3(value, val2=\"\"): TryClass.value +=",
"there data in the reading code? : dr_code=43534\") while not",
"metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until the reply",
"value, val2=\"\"): self.value += value print(f\"\\t>>> metod 1, add: {value},",
"val2=\"1\", dr_code=True) print(\"Metod 1, call, via bind to func\", dr_cls.dr_bind(code0,",
"== \"__main__\": try: from dirio import Dirio except: from ..dirio",
"print(\"Created TryClass :\", self) self.value = value def metod1(self, value,",
"= 4 v = 5 def __init__(self, value=4): print(\"Created TryClass",
"val2=\"1\", dr_wait=1)) print(\"Wait until the reply comes. metod 1 :\",",
"__name__ == \"__main__\": try: from dirio import Dirio except: from",
"print(\"We are waiting for the data with this code :\",",
"result\"\"\" print(f\"Bind Result, {result}\\n\"*10) print(\"other_arg\", other_arg) print(\"kwarg\", kwarg) if __name__",
"= 3 va = 4 v = 5 def __init__(self,",
"val2=\"2\", dr_code=True) print(\"Search by code only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying",
"dr_wait=-1)) code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1, call, via",
": {TryClass.value}, val2: {val2}\") return TryClass.value def event_call(other_arg, kwarg=\"-\", result=None):",
"val2: {val2}\") return TryClass.value def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this",
"print(\"kwarg\", kwarg) if __name__ == \"__main__\": try: from dirio import",
"= 2 print(f\"\\t>>> metod 2, add: {value}, now value :",
":\", dr_cls.metod2(10, val2=\"2\", dr_code=False)) print(\"Trying metod 3, called and returned",
"dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there data in",
"1 valu = 2 val = 3 va = 4",
"2 print(f\"\\t>>> metod 2, add: {value}, now value : {cls.value},",
"print(f\"\\t>>> metod 3, add: {value}, now value : {TryClass.value}, val2:",
"dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by code only",
"{self.value}, val2: {val2}\") time.sleep(2) return self.value @classmethod def metod2(cls, value,",
"return self.value @classmethod def metod2(cls, value, val2=\"\"): cls.value = 2",
"print(\"Search by code only :\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2,",
"print(f\"\\t>>> metod 1, add: {value}, now value : {self.value}, val2:",
"way give the last return value : nothing or dr_code=False\")",
"print(\"Methods called this way give the last return value :",
"code0 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Metod 1, call, via bind",
"TryClass.value def event_call(other_arg, kwarg=\"-\", result=None): \"\"\"Call this metod, on returned",
"val2=\"2\", dr_code=False)) print(\"Trying metod 3, called and returned :\", dr_cls.metod3(15,",
"def __init__(self, value=4): print(\"Created TryClass :\", self) self.value = value",
"print(\"Is there data in the reading code? : dr_code=43534\") while",
"code : dr_code=True\") code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there",
"{value}, now value : {self.value}, val2: {val2}\") time.sleep(2) return self.value",
"nothing or dr_code=False\") code2 = dr_cls.metod2(10, val2=\"2\", dr_code=True) print(\"Search by",
"{val2}\") time.sleep(2) return self.value @classmethod def metod2(cls, value, val2=\"\"): cls.value",
":\", dr_cls.dr_code(code2, wait=1)) print(\"Trying metod 2, called and returned :\",",
"TryClass :\", self) self.value = value def metod1(self, value, val2=\"\"):",
": {self.value}, val2: {val2}\") time.sleep(2) return self.value @classmethod def metod2(cls,",
"2, add: {value}, now value : {cls.value}, val2: {val2}\") return",
":\", dr_cls.metod1(dr_code=code1)) print(\"Methods called this way give the last return",
"if __name__ == \"__main__\": try: from dirio import Dirio except:",
"print(\"Trying metod 3, called and returned :\", dr_cls.metod3(15, val2=\"3\")) print(\"\\n\"*2)",
"return cls.value @staticmethod def metod3(value, val2=\"\"): TryClass.value += value print(f\"\\t>>>",
"@classmethod def metod2(cls, value, val2=\"\"): cls.value = 2 print(f\"\\t>>> metod",
"result=None): \"\"\"Call this metod, on returned result\"\"\" print(f\"Bind Result, {result}\\n\"*10)",
"4 v = 5 def __init__(self, value=4): print(\"Created TryClass :\",",
"print(\"Metod 1, call, via bind to func\", dr_cls.dr_bind(code0, event_call, args=(\"OtHeR",
"reading code? : dr_code=43534\") while not dr_cls.metod1(dr_code=code1): print(\"We are waiting",
"comes. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=-1)) code0 = dr_cls.metod1(5,",
"metod 2, add: {value}, now value : {cls.value}, val2: {val2}\")",
"+= value print(f\"\\t>>> metod 3, add: {value}, now value :",
"self.value += value print(f\"\\t>>> metod 1, add: {value}, now value",
"dr_cls = Dirio(target=TryClass, args=(888,), kwargs={}, worker=False) print(\"Starting values :\", dr_cls.value,",
"dirio import Dirio except: from ..dirio import Dirio dr_cls =",
"value, val2=\"\"): cls.value = 2 print(f\"\\t>>> metod 2, add: {value},",
"metod1(self, value, val2=\"\"): self.value += value print(f\"\\t>>> metod 1, add:",
"{value}, now value : {TryClass.value}, val2: {val2}\") return TryClass.value def",
"your reply. metod 1 :\", dr_cls.metod1(5, val2=\"1\", dr_wait=1)) print(\"Wait until",
"event_call, args=(\"OtHeR aRg\", ), kwargs={\"kwarg\": \"KwArG\"})) while True: # dr_cls.dr_binds_check()",
"worker=False) print(\"Starting values :\", dr_cls.value, dr_cls) print(\"\\n\"*2) print(\"Wait 1 sec",
"code1 = dr_cls.metod1(5, val2=\"1\", dr_code=True) print(\"Is there data in the"
] |
[
"configuration for the backend. If the backend does not support",
"configuration for the backend. \"\"\" return self._configuration def properties(self): \"\"\"Return",
"# Copyright 2017, IBM. # # This source code is",
"backend modules subclass the Backend class in this module. Doing",
"is not available. Args: configuration (BackendConfiguration): backend configuration provider (BaseProvider):",
"2017, IBM. # # This source code is licensed under",
"this backend Raises: FileNotFoundError if backend executable is not available.",
"provider @abstractmethod def run(self, qobj): \"\"\"Run a Qobj on the",
"the status of the backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True,",
"for backend modules. To create add-on backend modules subclass the",
"class in this module. Doing so requires that the required",
"licensed under the Apache License, Version 2.0 found in #",
"of the backend. \"\"\" return self._configuration.backend_name def __str__(self): return self.name()",
"status_msg='') def name(self): \"\"\"Return backend name. Returns: str: the name",
"string of the form <...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__",
"on the the backend.\"\"\" pass def configuration(self): \"\"\"Return the backend",
"the configuration for the backend. If the backend does not",
"Returns: str: the name of the backend. \"\"\" return self._configuration.backend_name",
"str: the name of the backend. \"\"\" return self._configuration.backend_name def",
"abstract base class for backend modules. To create add-on backend",
"To create add-on backend modules subclass the Backend class in",
"required backend interface is implemented. \"\"\" from abc import ABC,",
"the the backend.\"\"\" pass def configuration(self): \"\"\"Return the backend configuration.",
"component of the module is not available. Args: configuration (BackendConfiguration):",
"def configuration(self): \"\"\"Return the backend configuration. Returns: BackendConfiguration: the configuration",
"Returns: BackendProperties: the configuration for the backend. If the backend",
"raise an exception if a component of the module is",
"\"\"\" from abc import ABC, abstractmethod from qiskit.version import __version__",
"abstractmethod from qiskit.version import __version__ from .models import BackendStatus class",
"is no name in the configuration \"\"\" self._configuration = configuration",
"BackendConfiguration: the configuration for the backend. \"\"\" return self._configuration def",
"tree. \"\"\"This module implements the abstract base class for backend",
"pending_jobs=0, status_msg='') def name(self): \"\"\"Return backend name. Returns: str: the",
"\"\"\" return None def provider(self): \"\"\"Return the backend Provider. Returns:",
"that, by Qiskit convention, it is consciously *not* a fully",
"self._provider = provider @abstractmethod def run(self, qobj): \"\"\"Run a Qobj",
"def run(self, qobj): \"\"\"Run a Qobj on the the backend.\"\"\"",
"in the root directory of this source tree. \"\"\"This module",
"not available. QiskitError: if there is no name in the",
"available. QiskitError: if there is no name in the configuration",
"pass def configuration(self): \"\"\"Return the backend configuration. Returns: BackendConfiguration: the",
"implemented. \"\"\" from abc import ABC, abstractmethod from qiskit.version import",
"modules. To create add-on backend modules subclass the Backend class",
"return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self): \"\"\"Return backend",
"does not support properties, it returns ``None``. \"\"\" return None",
"the abstract base class for backend modules. To create add-on",
"= configuration self._provider = provider @abstractmethod def run(self, qobj): \"\"\"Run",
"= provider @abstractmethod def run(self, qobj): \"\"\"Run a Qobj on",
"provider responsible for this backend Raises: FileNotFoundError if backend executable",
"fully valid Python expression. Subclasses should provide 'a string of",
"subclass the Backend class in this module. Doing so requires",
"<...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return \"<{}('{}') from",
"responsible for this backend Raises: FileNotFoundError if backend executable is",
"self._provider def status(self): \"\"\"Return backend status. Returns: BackendStatus: the status",
"provider(self): \"\"\"Return the backend Provider. Returns: BaseProvider: the Provider responsible",
"consciously *not* a fully valid Python expression. Subclasses should provide",
"def __init__(self, configuration, provider=None): \"\"\"Base class for backends. This method",
"responsible for the backend. \"\"\" return self._provider def status(self): \"\"\"Return",
"-*- # Copyright 2017, IBM. # # This source code",
"module. Doing so requires that the required backend interface is",
"the Backend class in this module. Doing so requires that",
"License, Version 2.0 found in # the LICENSE.txt file in",
"create add-on backend modules subclass the Backend class in this",
"so requires that the required backend interface is implemented. \"\"\"",
"a Qobj on the the backend.\"\"\" pass def configuration(self): \"\"\"Return",
"2.0 found in # the LICENSE.txt file in the root",
"the backend Provider. Returns: BaseProvider: the Provider responsible for the",
"properties(self): \"\"\"Return backend properties. Returns: BackendProperties: the configuration for the",
"for the backend. \"\"\" return self._provider def status(self): \"\"\"Return backend",
"and its configuration, and raise an exception if a component",
"backend name. Returns: str: the name of the backend. \"\"\"",
"available. Args: configuration (BackendConfiguration): backend configuration provider (BaseProvider): provider responsible",
"__init__(self, configuration, provider=None): \"\"\"Base class for backends. This method should",
"initialize the module and its configuration, and raise an exception",
"for the backend. \"\"\" return self._configuration def properties(self): \"\"\"Return backend",
"configuration self._provider = provider @abstractmethod def run(self, qobj): \"\"\"Run a",
"add-on backend modules subclass the Backend class in this module.",
"from qiskit.version import __version__ from .models import BackendStatus class BaseBackend(ABC):",
"class for backends. This method should initialize the module and",
"backend configuration provider (BaseProvider): provider responsible for this backend Raises:",
"not support properties, it returns ``None``. \"\"\" return None def",
"base class for backend modules. To create add-on backend modules",
".models import BackendStatus class BaseBackend(ABC): \"\"\"Base class for backends.\"\"\" @abstractmethod",
"this module. Doing so requires that the required backend interface",
"__version__ from .models import BackendStatus class BaseBackend(ABC): \"\"\"Base class for",
"BaseBackend(ABC): \"\"\"Base class for backends.\"\"\" @abstractmethod def __init__(self, configuration, provider=None):",
"of the form <...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\"",
"\"\"\"Return backend status. Returns: BackendStatus: the status of the backend.",
"@abstractmethod def run(self, qobj): \"\"\"Run a Qobj on the the",
"if a component of the module is not available. Args:",
"Args: configuration (BackendConfiguration): backend configuration provider (BaseProvider): provider responsible for",
"backends.\"\"\" @abstractmethod def __init__(self, configuration, provider=None): \"\"\"Base class for backends.",
"FileNotFoundError if backend executable is not available. QiskitError: if there",
"executable is not available. QiskitError: if there is no name",
"it returns ``None``. \"\"\" return None def provider(self): \"\"\"Return the",
"module and its configuration, and raise an exception if a",
"provider=None): \"\"\"Base class for backends. This method should initialize the",
"backend. \"\"\" return self._provider def status(self): \"\"\"Return backend status. Returns:",
"root directory of this source tree. \"\"\"This module implements the",
"class for backend modules. To create add-on backend modules subclass",
"Raises: FileNotFoundError if backend executable is not available. QiskitError: if",
"backend.\"\"\" pass def configuration(self): \"\"\"Return the backend configuration. Returns: BackendConfiguration:",
"the backend. If the backend does not support properties, it",
"*not* a fully valid Python expression. Subclasses should provide 'a",
"Doing so requires that the required backend interface is implemented.",
"backend configuration. Returns: BackendConfiguration: the configuration for the backend. \"\"\"",
"return None def provider(self): \"\"\"Return the backend Provider. Returns: BaseProvider:",
"the backend configuration. Returns: BackendConfiguration: the configuration for the backend.",
"Backend. Note that, by Qiskit convention, it is consciously *not*",
"\"\"\"Base class for backends.\"\"\" @abstractmethod def __init__(self, configuration, provider=None): \"\"\"Base",
"class for backends.\"\"\" @abstractmethod def __init__(self, configuration, provider=None): \"\"\"Base class",
"@abstractmethod def __init__(self, configuration, provider=None): \"\"\"Base class for backends. This",
"backend Raises: FileNotFoundError if backend executable is not available. QiskitError:",
"\"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self): \"\"\"Return",
"def __repr__(self): \"\"\"Official string representation of a Backend. Note that,",
"self.name() def __repr__(self): \"\"\"Official string representation of a Backend. Note",
"the name of the backend. \"\"\" return self._configuration.backend_name def __str__(self):",
"abc import ABC, abstractmethod from qiskit.version import __version__ from .models",
"(BaseProvider): provider responsible for this backend Raises: FileNotFoundError if backend",
"coding: utf-8 -*- # Copyright 2017, IBM. # # This",
"def provider(self): \"\"\"Return the backend Provider. Returns: BaseProvider: the Provider",
"representation of a Backend. Note that, by Qiskit convention, it",
"the backend. \"\"\" return self._provider def status(self): \"\"\"Return backend status.",
"source code is licensed under the Apache License, Version 2.0",
"\"\"\"Return backend name. Returns: str: the name of the backend.",
"name in the configuration \"\"\" self._configuration = configuration self._provider =",
"the module and its configuration, and raise an exception if",
"\"\"\" self._configuration = configuration self._provider = provider @abstractmethod def run(self,",
"string representation of a Backend. Note that, by Qiskit convention,",
"the form <...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return",
"implements the abstract base class for backend modules. To create",
"Qobj on the the backend.\"\"\" pass def configuration(self): \"\"\"Return the",
"module implements the abstract base class for backend modules. To",
"the backend. \"\"\" return self._configuration.backend_name def __str__(self): return self.name() def",
"directory of this source tree. \"\"\"This module implements the abstract",
"module is not available. Args: configuration (BackendConfiguration): backend configuration provider",
"def __str__(self): return self.name() def __repr__(self): \"\"\"Official string representation of",
"Qiskit convention, it is consciously *not* a fully valid Python",
"the configuration \"\"\" self._configuration = configuration self._provider = provider @abstractmethod",
"Python expression. Subclasses should provide 'a string of the form",
"utf-8 -*- # Copyright 2017, IBM. # # This source",
"# This source code is licensed under the Apache License,",
"backend. If the backend does not support properties, it returns",
"\"\"\" return self._provider def status(self): \"\"\"Return backend status. Returns: BackendStatus:",
"of the backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='')",
"in this module. Doing so requires that the required backend",
"if there is no name in the configuration \"\"\" self._configuration",
"requires that the required backend interface is implemented. \"\"\" from",
"\"\"\" return self._configuration.backend_name def __str__(self): return self.name() def __repr__(self): \"\"\"Official",
"This method should initialize the module and its configuration, and",
"provider (BaseProvider): provider responsible for this backend Raises: FileNotFoundError if",
"properties. Returns: BackendProperties: the configuration for the backend. If the",
"\"\"\"Return backend properties. Returns: BackendProperties: the configuration for the backend.",
"under the Apache License, Version 2.0 found in # the",
"``None``. \"\"\" return None def provider(self): \"\"\"Return the backend Provider.",
"Provider. Returns: BaseProvider: the Provider responsible for the backend. \"\"\"",
"a Backend. Note that, by Qiskit convention, it is consciously",
"import ABC, abstractmethod from qiskit.version import __version__ from .models import",
"backend properties. Returns: BackendProperties: the configuration for the backend. If",
"convention, it is consciously *not* a fully valid Python expression.",
"Copyright 2017, IBM. # # This source code is licensed",
"in # the LICENSE.txt file in the root directory of",
"Note that, by Qiskit convention, it is consciously *not* a",
"of the module is not available. Args: configuration (BackendConfiguration): backend",
"its configuration, and raise an exception if a component of",
"\"\"\"Return the backend configuration. Returns: BackendConfiguration: the configuration for the",
"method should initialize the module and its configuration, and raise",
"backend. \"\"\" return self._configuration def properties(self): \"\"\"Return backend properties. Returns:",
"backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self): \"\"\"Return backend name. Returns:",
"support properties, it returns ``None``. \"\"\" return None def provider(self):",
"IBM. # # This source code is licensed under the",
"configuration, and raise an exception if a component of the",
"the configuration for the backend. \"\"\" return self._configuration def properties(self):",
"[0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return \"<{}('{}') from {}()>\".format(self.__class__.__name__, self.name(), self._provider)",
"backend interface is implemented. \"\"\" from abc import ABC, abstractmethod",
"BackendStatus class BaseBackend(ABC): \"\"\"Base class for backends.\"\"\" @abstractmethod def __init__(self,",
"valid Python expression. Subclasses should provide 'a string of the",
"status. Returns: BackendStatus: the status of the backend. \"\"\" return",
"is implemented. \"\"\" from abc import ABC, abstractmethod from qiskit.version",
"return self._configuration.backend_name def __str__(self): return self.name() def __repr__(self): \"\"\"Official string",
"backend status. Returns: BackendStatus: the status of the backend. \"\"\"",
"description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return \"<{}('{}') from {}()>\".format(self.__class__.__name__, self.name(),",
"Backend class in this module. Doing so requires that the",
"operational=True, pending_jobs=0, status_msg='') def name(self): \"\"\"Return backend name. Returns: str:",
"Apache License, Version 2.0 found in # the LICENSE.txt file",
"no name in the configuration \"\"\" self._configuration = configuration self._provider",
"returns ``None``. \"\"\" return None def provider(self): \"\"\"Return the backend",
"return self._configuration def properties(self): \"\"\"Return backend properties. Returns: BackendProperties: the",
"Returns: BackendStatus: the status of the backend. \"\"\" return BackendStatus(backend_name=self.name(),",
"code is licensed under the Apache License, Version 2.0 found",
"class BaseBackend(ABC): \"\"\"Base class for backends.\"\"\" @abstractmethod def __init__(self, configuration,",
"\"\"\"Run a Qobj on the the backend.\"\"\" pass def configuration(self):",
"configuration(self): \"\"\"Return the backend configuration. Returns: BackendConfiguration: the configuration for",
"for backends. This method should initialize the module and its",
"self._configuration def properties(self): \"\"\"Return backend properties. Returns: BackendProperties: the configuration",
"source tree. \"\"\"This module implements the abstract base class for",
"should provide 'a string of the form <...some useful description...>'.",
"backend does not support properties, it returns ``None``. \"\"\" return",
"LICENSE.txt file in the root directory of this source tree.",
"not available. Args: configuration (BackendConfiguration): backend configuration provider (BaseProvider): provider",
"for backends.\"\"\" @abstractmethod def __init__(self, configuration, provider=None): \"\"\"Base class for",
"None def provider(self): \"\"\"Return the backend Provider. Returns: BaseProvider: the",
"return self._provider def status(self): \"\"\"Return backend status. Returns: BackendStatus: the",
"name of the backend. \"\"\" return self._configuration.backend_name def __str__(self): return",
"(BackendConfiguration): backend configuration provider (BaseProvider): provider responsible for this backend",
"by Qiskit convention, it is consciously *not* a fully valid",
"\"\"\"Official string representation of a Backend. Note that, by Qiskit",
"a component of the module is not available. Args: configuration",
"it is consciously *not* a fully valid Python expression. Subclasses",
"self._configuration = configuration self._provider = provider @abstractmethod def run(self, qobj):",
"return self.name() def __repr__(self): \"\"\"Official string representation of a Backend.",
"\"\"\"Base class for backends. This method should initialize the module",
"the backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def",
"backends. This method should initialize the module and its configuration,",
"for the backend. If the backend does not support properties,",
"\"\"\"Return the backend Provider. Returns: BaseProvider: the Provider responsible for",
"is consciously *not* a fully valid Python expression. Subclasses should",
"found in # the LICENSE.txt file in the root directory",
"# -*- coding: utf-8 -*- # Copyright 2017, IBM. #",
"qiskit.version import __version__ from .models import BackendStatus class BaseBackend(ABC): \"\"\"Base",
"import BackendStatus class BaseBackend(ABC): \"\"\"Base class for backends.\"\"\" @abstractmethod def",
"# the LICENSE.txt file in the root directory of this",
"BackendProperties: the configuration for the backend. If the backend does",
"__str__(self): return self.name() def __repr__(self): \"\"\"Official string representation of a",
"This source code is licensed under the Apache License, Version",
"qobj): \"\"\"Run a Qobj on the the backend.\"\"\" pass def",
"'a string of the form <...some useful description...>'. [0] [0]",
"is not available. QiskitError: if there is no name in",
"provide 'a string of the form <...some useful description...>'. [0]",
"name. Returns: str: the name of the backend. \"\"\" return",
"useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return \"<{}('{}') from {}()>\".format(self.__class__.__name__,",
"modules subclass the Backend class in this module. Doing so",
"of this source tree. \"\"\"This module implements the abstract base",
"properties, it returns ``None``. \"\"\" return None def provider(self): \"\"\"Return",
"backend Provider. Returns: BaseProvider: the Provider responsible for the backend.",
"configuration (BackendConfiguration): backend configuration provider (BaseProvider): provider responsible for this",
"backend executable is not available. QiskitError: if there is no",
"backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self):",
"of a Backend. Note that, by Qiskit convention, it is",
"__repr__(self): \"\"\"Official string representation of a Backend. Note that, by",
"in the configuration \"\"\" self._configuration = configuration self._provider = provider",
"self._configuration.backend_name def __str__(self): return self.name() def __repr__(self): \"\"\"Official string representation",
"configuration \"\"\" self._configuration = configuration self._provider = provider @abstractmethod def",
"the Apache License, Version 2.0 found in # the LICENSE.txt",
"a fully valid Python expression. Subclasses should provide 'a string",
"if backend executable is not available. QiskitError: if there is",
"backend. \"\"\" return self._configuration.backend_name def __str__(self): return self.name() def __repr__(self):",
"\"\"\"This module implements the abstract base class for backend modules.",
"this source tree. \"\"\"This module implements the abstract base class",
"the root directory of this source tree. \"\"\"This module implements",
"BaseProvider: the Provider responsible for the backend. \"\"\" return self._provider",
"status of the backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0,",
"-*- coding: utf-8 -*- # Copyright 2017, IBM. # #",
"the required backend interface is implemented. \"\"\" from abc import",
"QiskitError: if there is no name in the configuration \"\"\"",
"there is no name in the configuration \"\"\" self._configuration =",
"the Provider responsible for the backend. \"\"\" return self._provider def",
"an exception if a component of the module is not",
"status(self): \"\"\"Return backend status. Returns: BackendStatus: the status of the",
"is licensed under the Apache License, Version 2.0 found in",
"that the required backend interface is implemented. \"\"\" from abc",
"exception if a component of the module is not available.",
"from .models import BackendStatus class BaseBackend(ABC): \"\"\"Base class for backends.\"\"\"",
"Returns: BaseProvider: the Provider responsible for the backend. \"\"\" return",
"BackendStatus(backend_name=self.name(), backend_version=__version__, operational=True, pending_jobs=0, status_msg='') def name(self): \"\"\"Return backend name.",
"Subclasses should provide 'a string of the form <...some useful",
"BackendStatus: the status of the backend. \"\"\" return BackendStatus(backend_name=self.name(), backend_version=__version__,",
"should initialize the module and its configuration, and raise an",
"import __version__ from .models import BackendStatus class BaseBackend(ABC): \"\"\"Base class",
"for this backend Raises: FileNotFoundError if backend executable is not",
"ABC, abstractmethod from qiskit.version import __version__ from .models import BackendStatus",
"file in the root directory of this source tree. \"\"\"This",
"the backend does not support properties, it returns ``None``. \"\"\"",
"Returns: BackendConfiguration: the configuration for the backend. \"\"\" return self._configuration",
"from abc import ABC, abstractmethod from qiskit.version import __version__ from",
"def name(self): \"\"\"Return backend name. Returns: str: the name of",
"If the backend does not support properties, it returns ``None``.",
"run(self, qobj): \"\"\"Run a Qobj on the the backend.\"\"\" pass",
"\"\"\" return self._configuration def properties(self): \"\"\"Return backend properties. Returns: BackendProperties:",
"the backend.\"\"\" pass def configuration(self): \"\"\"Return the backend configuration. Returns:",
"interface is implemented. \"\"\" from abc import ABC, abstractmethod from",
"Provider responsible for the backend. \"\"\" return self._provider def status(self):",
"name(self): \"\"\"Return backend name. Returns: str: the name of the",
"# # This source code is licensed under the Apache",
"configuration. Returns: BackendConfiguration: the configuration for the backend. \"\"\" return",
"the module is not available. Args: configuration (BackendConfiguration): backend configuration",
"form <...some useful description...>'. [0] [0] https://docs.python.org/3/reference/datamodel.html#object.__repr__ \"\"\" return \"<{}('{}')",
"<reponame>ismaila-at-za-ibm/qiskit-terra<filename>qiskit/providers/basebackend.py # -*- coding: utf-8 -*- # Copyright 2017, IBM.",
"configuration, provider=None): \"\"\"Base class for backends. This method should initialize",
"def status(self): \"\"\"Return backend status. Returns: BackendStatus: the status of",
"expression. Subclasses should provide 'a string of the form <...some",
"the backend. \"\"\" return self._configuration def properties(self): \"\"\"Return backend properties.",
"configuration provider (BaseProvider): provider responsible for this backend Raises: FileNotFoundError",
"backend modules. To create add-on backend modules subclass the Backend",
"Version 2.0 found in # the LICENSE.txt file in the",
"def properties(self): \"\"\"Return backend properties. Returns: BackendProperties: the configuration for",
"the LICENSE.txt file in the root directory of this source",
"and raise an exception if a component of the module"
] |
[
"you can land anywhere between l & r+1 in a",
"< len(nums)-1 : jumps += 1 # you can land",
"+= 1 # you can land anywhere between l &",
"for i in range(l, r+1)) l , r = r,",
"0, nums[0] , 1 while r < len(nums)-1 : jumps",
"int: if len(nums) <=1: return 0 l , r ,",
"List[int]) -> int: if len(nums) <=1: return 0 l ,",
"in range(l, r+1)) l , r = r, nxt return",
"i + nums[i] for i in range(l, r+1)) l ,",
"-> int: if len(nums) <=1: return 0 l , r",
"nxt return jumps s = Solution() ans = s.jump([3,2,1,0,4]) print(ans)",
"from there nxt = max( i + nums[i] for i",
"there nxt = max( i + nums[i] for i in",
"and then use Num[i] to jump from there nxt =",
"range(l, r+1)) l , r = r, nxt return jumps",
"# you can land anywhere between l & r+1 in",
"r+1 in a jump and then use Num[i] to jump",
"if len(nums) <=1: return 0 l , r , jumps",
"while r < len(nums)-1 : jumps += 1 # you",
": jumps += 1 # you can land anywhere between",
"List import sys class Solution: def jump(self, nums: List[int]) ->",
"Solution: def jump(self, nums: List[int]) -> int: if len(nums) <=1:",
"Num[i] to jump from there nxt = max( i +",
"nums[i] for i in range(l, r+1)) l , r =",
"r < len(nums)-1 : jumps += 1 # you can",
"between l & r+1 in a jump and then use",
"r, nxt return jumps s = Solution() ans = s.jump([3,2,1,0,4])",
"0 l , r , jumps = 0, nums[0] ,",
"sys class Solution: def jump(self, nums: List[int]) -> int: if",
"& r+1 in a jump and then use Num[i] to",
"l , r , jumps = 0, nums[0] , 1",
"in a jump and then use Num[i] to jump from",
", r , jumps = 0, nums[0] , 1 while",
"then use Num[i] to jump from there nxt = max(",
"i in range(l, r+1)) l , r = r, nxt",
"land anywhere between l & r+1 in a jump and",
"jump from there nxt = max( i + nums[i] for",
", r = r, nxt return jumps s = Solution()",
"return 0 l , r , jumps = 0, nums[0]",
"import sys class Solution: def jump(self, nums: List[int]) -> int:",
"jumps = 0, nums[0] , 1 while r < len(nums)-1",
"jump(self, nums: List[int]) -> int: if len(nums) <=1: return 0",
", 1 while r < len(nums)-1 : jumps += 1",
"r , jumps = 0, nums[0] , 1 while r",
"nums[0] , 1 while r < len(nums)-1 : jumps +=",
"len(nums) <=1: return 0 l , r , jumps =",
"max( i + nums[i] for i in range(l, r+1)) l",
"import List import sys class Solution: def jump(self, nums: List[int])",
"= max( i + nums[i] for i in range(l, r+1))",
"from typing import List import sys class Solution: def jump(self,",
"= r, nxt return jumps s = Solution() ans =",
"to jump from there nxt = max( i + nums[i]",
"r+1)) l , r = r, nxt return jumps s",
"r = r, nxt return jumps s = Solution() ans",
"l , r = r, nxt return jumps s =",
"def jump(self, nums: List[int]) -> int: if len(nums) <=1: return",
"nums: List[int]) -> int: if len(nums) <=1: return 0 l",
"= 0, nums[0] , 1 while r < len(nums)-1 :",
"a jump and then use Num[i] to jump from there",
"anywhere between l & r+1 in a jump and then",
"typing import List import sys class Solution: def jump(self, nums:",
"jump and then use Num[i] to jump from there nxt",
"<=1: return 0 l , r , jumps = 0,",
"jumps += 1 # you can land anywhere between l",
"can land anywhere between l & r+1 in a jump",
", jumps = 0, nums[0] , 1 while r <",
"1 while r < len(nums)-1 : jumps += 1 #",
"use Num[i] to jump from there nxt = max( i",
"1 # you can land anywhere between l & r+1",
"nxt = max( i + nums[i] for i in range(l,",
"len(nums)-1 : jumps += 1 # you can land anywhere",
"l & r+1 in a jump and then use Num[i]",
"+ nums[i] for i in range(l, r+1)) l , r",
"class Solution: def jump(self, nums: List[int]) -> int: if len(nums)"
] |
[
". import states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState()",
"self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( collect_pending_state.apply(cancelled_event), states.InvalidState",
"= states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance(",
"from . import states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue =",
"approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState )",
"self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event",
"= states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance(",
"cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event = states.DonationDispatchedEvent()",
"= states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance(",
"states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState()",
"collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( collect_pending_state.apply(cancelled_event), states.InvalidState )",
"states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event =",
"states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event =",
"cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event = states.DonationApprovedEvent()",
"= states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self): collect_pending_state =",
"states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState()",
"test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState",
"donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event = states.DonationCancelledEvent()",
"approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self): collect_pending_state",
"= states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event",
") def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance(",
"self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState",
") def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance(",
"approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event =",
"= states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event",
"dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event =",
"dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, )",
"collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event = states.DonationCancelledEvent()",
"= states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance(",
"states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event =",
"states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event),",
"states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event",
"def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event),",
"states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event),",
"dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state",
"self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState",
"self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event",
"collect_pending_state = states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState )",
"import unittest from . import states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self):",
"class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event = states.DonationApprovedEvent()",
"test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState,",
"= states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event",
"= states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state =",
") approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def test_collect_pending_state(self):",
"self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState",
"approve_pending_statue = states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, )",
"dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState )",
"states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event), states.DoneState ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( collect_pending_state.apply(cancelled_event),",
"states.DoneState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event",
"def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent() self.assertIsInstance( collect_pending_state.apply(collected_event),",
"states.InvalidState ) def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent()",
"self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState",
"DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance(",
"states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event),",
"states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event =",
") cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState ) dispatch_event =",
"test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState,",
"def test_dispatch_pending_state(self): dispatch_pending_state = states.PendingDispatchState() donation_dispatched_event = states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event),",
"unittest from . import states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue",
"states.InvalidState ) def test_collect_pending_state(self): collect_pending_state = states.PendingDeliveryState() collected_event = states.DonationDeliveredEvent()",
") dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def test_dispatch_pending_state(self):",
"dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState )",
"approved_event = states.DonationApprovedEvent() self.assertIsInstance( approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent()",
"states.CancelledState ) approved_event = states.DonationApprovedEvent() self.assertIsInstance( dispatch_pending_state.apply(approved_event), states.InvalidState ) def",
"= states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event = states.DonationApprovedEvent() self.assertIsInstance(",
") cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event), states.CancelledState ) approved_event =",
"approve_pending_statue.apply(approved_event), states.PendingDispatchState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( approve_pending_statue.apply(cancelled_event), states.CancelledState )",
"import states class DonationStateTestCase(unittest.TestCase): def test_approve_pending_state(self): approve_pending_statue = states.PendingApprovalState() approved_event",
"states.CancelledState ) dispatch_event = states.DonationDispatchedEvent() self.assertIsInstance( approve_pending_statue.apply(dispatch_event), states.InvalidState ) def",
"states.DonationDispatchedEvent() self.assertIsInstance( dispatch_pending_state.apply(donation_dispatched_event), states.DoneState, ) cancelled_event = states.DonationCancelledEvent() self.assertIsInstance( dispatch_pending_state.apply(cancelled_event),"
] |
[
"expression that is used as cache key. args = [parser.parse_expression()]",
"a `CallBlock` node that calls our _cache_support # helper method",
"drop_needle=True) # now return a `CallBlock` node that calls our",
"to `endcache` and # drop the needle (which would always",
"be a name token with # `cache` as value. We",
"our case # we only listen to ``'cache'`` so this",
"class FragmentCacheExtension(Extension): # a set of names that trigger the",
"key. args = [parser.parse_expression()] # if there is a comma,",
"cache key. args = [parser.parse_expression()] # if there is a",
") def parse(self, parser): # the first token is the",
"not use # None as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression())",
"the body of the cache block up to `endcache` and",
"# helper method on this extension. return nodes.CallBlock(self.call_method('_cache_support', args), [],",
"defaults to the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self,",
"the line number so that we can give # that",
"we parse a single expression that is used as cache",
"is used as cache key. args = [parser.parse_expression()] # if",
"hand. lineno = next(parser.stream).lineno # now we parse a single",
"rv is not None: return rv rv = caller() self.environment.fragment_cache.add(key,",
"cache, render it and store # it in the cache.",
"always be `endcache` in that case) body = parser.parse_statements(['name:endcache'], drop_needle=True)",
"only listen to ``'cache'`` so this will be a name",
"tags = set(['cache']) def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) # add",
"None as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) #",
"now we parse the body of the cache block up",
"from jinja2 import nodes from jinja2.ext import Extension class FragmentCacheExtension(Extension):",
"fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self, parser): # the first token",
"the nodes we create by hand. lineno = next(parser.stream).lineno #",
"= self.environment.fragment_cache.get(key) if rv is not None: return rv rv",
"a set of names that trigger the extension. tags =",
"`endcache` in that case) body = parser.parse_statements(['name:endcache'], drop_needle=True) # now",
"args = [parser.parse_expression()] # if there is a comma, the",
"be `endcache` in that case) body = parser.parse_statements(['name:endcache'], drop_needle=True) #",
"return nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno) def _cache_support(self, name, timeout,",
"self).__init__(environment) # add the defaults to the environment environment.extend( fragment_cache_prefix='fragment',",
"jinja2.ext import Extension class FragmentCacheExtension(Extension): # a set of names",
"a name token with # `cache` as value. We get",
"that is used as cache key. args = [parser.parse_expression()] #",
"provided a timeout. If not use # None as second",
"a timeout. If not use # None as second parameter.",
"block up to `endcache` and # drop the needle (which",
"caller): \"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix + name # try",
"to load the block from the cache # if there",
"fragment in the cache, render it and store # it",
"store # it in the cache. rv = self.environment.fragment_cache.get(key) if",
"that we can give # that line number to the",
"tag. In our case # we only listen to ``'cache'``",
"In our case # we only listen to ``'cache'`` so",
"listen to ``'cache'`` so this will be a name token",
"add the defaults to the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None )",
"args), [], [], body).set_lineno(lineno) def _cache_support(self, name, timeout, caller): \"\"\"Helper",
"line number so that we can give # that line",
"environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self, parser): # the",
"def parse(self, parser): # the first token is the token",
"def _cache_support(self, name, timeout, caller): \"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix",
"give # that line number to the nodes we create",
"key = self.environment.fragment_cache_prefix + name # try to load the",
"started the tag. In our case # we only listen",
"lineno = next(parser.stream).lineno # now we parse a single expression",
"from jinja2.ext import Extension class FragmentCacheExtension(Extension): # a set of",
"the cache # if there is no fragment in the",
"parse(self, parser): # the first token is the token that",
"get the line number so that we can give #",
"will be a name token with # `cache` as value.",
"timeout. If not use # None as second parameter. if",
"our _cache_support # helper method on this extension. return nodes.CallBlock(self.call_method('_cache_support',",
"[], [], body).set_lineno(lineno) def _cache_support(self, name, timeout, caller): \"\"\"Helper callback.\"\"\"",
"not None: return rv rv = caller() self.environment.fragment_cache.add(key, rv, timeout)",
"calls our _cache_support # helper method on this extension. return",
"# add the defaults to the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None",
"timeout, caller): \"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix + name #",
"to the nodes we create by hand. lineno = next(parser.stream).lineno",
"`endcache` and # drop the needle (which would always be",
"environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self, parser): # the first",
"case) body = parser.parse_statements(['name:endcache'], drop_needle=True) # now return a `CallBlock`",
"of names that trigger the extension. tags = set(['cache']) def",
"line number to the nodes we create by hand. lineno",
"the defaults to the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def",
"the cache. rv = self.environment.fragment_cache.get(key) if rv is not None:",
"that line number to the nodes we create by hand.",
"the needle (which would always be `endcache` in that case)",
"there is a comma, the user provided a timeout. If",
"callback.\"\"\" key = self.environment.fragment_cache_prefix + name # try to load",
"no fragment in the cache, render it and store #",
"name # try to load the block from the cache",
"if there is no fragment in the cache, render it",
"in that case) body = parser.parse_statements(['name:endcache'], drop_needle=True) # now return",
"render it and store # it in the cache. rv",
"rv = self.environment.fragment_cache.get(key) if rv is not None: return rv",
"jinja2 import nodes from jinja2.ext import Extension class FragmentCacheExtension(Extension): #",
"the block from the cache # if there is no",
"second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we",
"parser): # the first token is the token that started",
"nodes we create by hand. lineno = next(parser.stream).lineno # now",
"# now return a `CallBlock` node that calls our _cache_support",
"Extension class FragmentCacheExtension(Extension): # a set of names that trigger",
"# we only listen to ``'cache'`` so this will be",
"in the cache, render it and store # it in",
"we parse the body of the cache block up to",
"cache # if there is no fragment in the cache,",
"can give # that line number to the nodes we",
"it in the cache. rv = self.environment.fragment_cache.get(key) if rv is",
"comma, the user provided a timeout. If not use #",
"self.environment.fragment_cache.get(key) if rv is not None: return rv rv =",
"parse a single expression that is used as cache key.",
"a comma, the user provided a timeout. If not use",
"(which would always be `endcache` in that case) body =",
"the user provided a timeout. If not use # None",
"= self.environment.fragment_cache_prefix + name # try to load the block",
"that case) body = parser.parse_statements(['name:endcache'], drop_needle=True) # now return a",
"drop the needle (which would always be `endcache` in that",
"number so that we can give # that line number",
"node that calls our _cache_support # helper method on this",
"helper method on this extension. return nodes.CallBlock(self.call_method('_cache_support', args), [], [],",
"a single expression that is used as cache key. args",
"args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we parse the body of",
"token with # `cache` as value. We get the line",
"\"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix + name # try to",
"return a `CallBlock` node that calls our _cache_support # helper",
"# drop the needle (which would always be `endcache` in",
"set of names that trigger the extension. tags = set(['cache'])",
"names that trigger the extension. tags = set(['cache']) def __init__(self,",
"that trigger the extension. tags = set(['cache']) def __init__(self, environment):",
"+ name # try to load the block from the",
"# if there is a comma, the user provided a",
"extension. return nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno) def _cache_support(self, name,",
"# if there is no fragment in the cache, render",
"environment): super(FragmentCacheExtension, self).__init__(environment) # add the defaults to the environment",
"# None as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None))",
"FragmentCacheExtension(Extension): # a set of names that trigger the extension.",
"we can give # that line number to the nodes",
"parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we parse",
"args.append(nodes.Const(None)) # now we parse the body of the cache",
"`CallBlock` node that calls our _cache_support # helper method on",
"is not None: return rv rv = caller() self.environment.fragment_cache.add(key, rv,",
"load the block from the cache # if there is",
"the cache block up to `endcache` and # drop the",
"`cache` as value. We get the line number so that",
"_cache_support(self, name, timeout, caller): \"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix +",
"so that we can give # that line number to",
"nodes from jinja2.ext import Extension class FragmentCacheExtension(Extension): # a set",
"import Extension class FragmentCacheExtension(Extension): # a set of names that",
"trigger the extension. tags = set(['cache']) def __init__(self, environment): super(FragmentCacheExtension,",
"# a set of names that trigger the extension. tags",
"extension. tags = set(['cache']) def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) #",
"number to the nodes we create by hand. lineno =",
"else: args.append(nodes.Const(None)) # now we parse the body of the",
"by hand. lineno = next(parser.stream).lineno # now we parse a",
"[parser.parse_expression()] # if there is a comma, the user provided",
"we only listen to ``'cache'`` so this will be a",
"name token with # `cache` as value. We get the",
"on this extension. return nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno) def",
"= parser.parse_statements(['name:endcache'], drop_needle=True) # now return a `CallBlock` node that",
"__init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) # add the defaults to the",
"# now we parse the body of the cache block",
"cache block up to `endcache` and # drop the needle",
"If not use # None as second parameter. if parser.stream.skip_if('comma'):",
"of the cache block up to `endcache` and # drop",
"value. We get the line number so that we can",
"self.environment.fragment_cache_prefix + name # try to load the block from",
"single expression that is used as cache key. args =",
"user provided a timeout. If not use # None as",
"token that started the tag. In our case # we",
"the extension. tags = set(['cache']) def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment)",
"cache. rv = self.environment.fragment_cache.get(key) if rv is not None: return",
"None: return rv rv = caller() self.environment.fragment_cache.add(key, rv, timeout) return",
"to the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self, parser):",
"_cache_support # helper method on this extension. return nodes.CallBlock(self.call_method('_cache_support', args),",
"parse the body of the cache block up to `endcache`",
"case # we only listen to ``'cache'`` so this will",
"= next(parser.stream).lineno # now we parse a single expression that",
"we create by hand. lineno = next(parser.stream).lineno # now we",
"as value. We get the line number so that we",
"is the token that started the tag. In our case",
"We get the line number so that we can give",
"with # `cache` as value. We get the line number",
"if there is a comma, the user provided a timeout.",
"up to `endcache` and # drop the needle (which would",
"and # drop the needle (which would always be `endcache`",
"is no fragment in the cache, render it and store",
"and store # it in the cache. rv = self.environment.fragment_cache.get(key)",
"fragment_cache=None ) def parse(self, parser): # the first token is",
"to ``'cache'`` so this will be a name token with",
"# now we parse a single expression that is used",
"parser.parse_statements(['name:endcache'], drop_needle=True) # now return a `CallBlock` node that calls",
"there is no fragment in the cache, render it and",
"this extension. return nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno) def _cache_support(self,",
"if rv is not None: return rv rv = caller()",
"block from the cache # if there is no fragment",
"return rv rv = caller() self.environment.fragment_cache.add(key, rv, timeout) return rv",
"body).set_lineno(lineno) def _cache_support(self, name, timeout, caller): \"\"\"Helper callback.\"\"\" key =",
"def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) # add the defaults to",
"in the cache. rv = self.environment.fragment_cache.get(key) if rv is not",
"needle (which would always be `endcache` in that case) body",
"name, timeout, caller): \"\"\"Helper callback.\"\"\" key = self.environment.fragment_cache_prefix + name",
"use # None as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else:",
"# it in the cache. rv = self.environment.fragment_cache.get(key) if rv",
"= [parser.parse_expression()] # if there is a comma, the user",
"= set(['cache']) def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) # add the",
"``'cache'`` so this will be a name token with #",
"now return a `CallBlock` node that calls our _cache_support #",
"body = parser.parse_statements(['name:endcache'], drop_needle=True) # now return a `CallBlock` node",
"# the first token is the token that started the",
"parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we parse the body",
"the cache, render it and store # it in the",
"that calls our _cache_support # helper method on this extension.",
"# that line number to the nodes we create by",
"if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now we parse the",
"super(FragmentCacheExtension, self).__init__(environment) # add the defaults to the environment environment.extend(",
"set(['cache']) def __init__(self, environment): super(FragmentCacheExtension, self).__init__(environment) # add the defaults",
"the first token is the token that started the tag.",
"the environment environment.extend( fragment_cache_prefix='fragment', fragment_cache=None ) def parse(self, parser): #",
"as cache key. args = [parser.parse_expression()] # if there is",
"that started the tag. In our case # we only",
"method on this extension. return nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno)",
"# try to load the block from the cache #",
"body of the cache block up to `endcache` and #",
"it and store # it in the cache. rv =",
"first token is the token that started the tag. In",
"try to load the block from the cache # if",
"would always be `endcache` in that case) body = parser.parse_statements(['name:endcache'],",
"create by hand. lineno = next(parser.stream).lineno # now we parse",
"[], body).set_lineno(lineno) def _cache_support(self, name, timeout, caller): \"\"\"Helper callback.\"\"\" key",
"used as cache key. args = [parser.parse_expression()] # if there",
"token is the token that started the tag. In our",
"nodes.CallBlock(self.call_method('_cache_support', args), [], [], body).set_lineno(lineno) def _cache_support(self, name, timeout, caller):",
"this will be a name token with # `cache` as",
"as second parameter. if parser.stream.skip_if('comma'): args.append(parser.parse_expression()) else: args.append(nodes.Const(None)) # now",
"# `cache` as value. We get the line number so",
"now we parse a single expression that is used as",
"next(parser.stream).lineno # now we parse a single expression that is",
"from the cache # if there is no fragment in",
"is a comma, the user provided a timeout. If not",
"import nodes from jinja2.ext import Extension class FragmentCacheExtension(Extension): # a",
"the tag. In our case # we only listen to",
"so this will be a name token with # `cache`",
"the token that started the tag. In our case #"
] |
[
"open(pdb, 'r') as x: lines = x.readlines() for i in",
"for changing the current working directory\"\"\" def __init__(self, newPath): self.newPath",
"newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath)",
"def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value,",
"'r') as x: lines = x.readlines() for i in lines:",
"molecule_number = count + 1 break return molecule_number class cd:",
"class cd: \"\"\"Context manager for changing the current working directory\"\"\"",
"with open(pdb, 'r') as x: lines = x.readlines() for i",
"count = 0 with open(pdb, 'r') as x: lines =",
"+ 1 break return molecule_number class cd: \"\"\"Context manager for",
"def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath =",
"if i.split()[3] == resname: molecule_number = count + 1 break",
"= count + 1 break return molecule_number class cd: \"\"\"Context",
"__init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd()",
"0 with open(pdb, 'r') as x: lines = x.readlines() for",
"the current working directory\"\"\" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath)",
"x: lines = x.readlines() for i in lines: if i.split()[0]",
"os def retrieve_molecule_number(pdb, resname): \"\"\" IDENTIFICATION OF MOLECULE NUMBER BASED",
"manager for changing the current working directory\"\"\" def __init__(self, newPath):",
"x.readlines() for i in lines: if i.split()[0] == 'TER': count",
"MOLECULE NUMBER BASED ON THE TER'S \"\"\" count = 0",
"= x.readlines() for i in lines: if i.split()[0] == 'TER':",
"'TER': count += 1 if i.split()[3] == resname: molecule_number =",
"\"\"\"Context manager for changing the current working directory\"\"\" def __init__(self,",
"+= 1 if i.split()[3] == resname: molecule_number = count +",
"self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback): os.chdir(self.savedPath)",
"as x: lines = x.readlines() for i in lines: if",
"\"\"\" IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S \"\"\"",
"BASED ON THE TER'S \"\"\" count = 0 with open(pdb,",
"directory\"\"\" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath",
"def retrieve_molecule_number(pdb, resname): \"\"\" IDENTIFICATION OF MOLECULE NUMBER BASED ON",
"\"\"\" count = 0 with open(pdb, 'r') as x: lines",
"for i in lines: if i.split()[0] == 'TER': count +=",
"retrieve_molecule_number(pdb, resname): \"\"\" IDENTIFICATION OF MOLECULE NUMBER BASED ON THE",
"count + 1 break return molecule_number class cd: \"\"\"Context manager",
"return molecule_number class cd: \"\"\"Context manager for changing the current",
"i.split()[0] == 'TER': count += 1 if i.split()[3] == resname:",
"i.split()[3] == resname: molecule_number = count + 1 break return",
"current working directory\"\"\" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def",
"= 0 with open(pdb, 'r') as x: lines = x.readlines()",
"if i.split()[0] == 'TER': count += 1 if i.split()[3] ==",
"lines = x.readlines() for i in lines: if i.split()[0] ==",
"cd: \"\"\"Context manager for changing the current working directory\"\"\" def",
"NUMBER BASED ON THE TER'S \"\"\" count = 0 with",
"in lines: if i.split()[0] == 'TER': count += 1 if",
"__enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype, value, traceback):",
"ON THE TER'S \"\"\" count = 0 with open(pdb, 'r')",
"OF MOLECULE NUMBER BASED ON THE TER'S \"\"\" count =",
"1 if i.split()[3] == resname: molecule_number = count + 1",
"== resname: molecule_number = count + 1 break return molecule_number",
"1 break return molecule_number class cd: \"\"\"Context manager for changing",
"resname: molecule_number = count + 1 break return molecule_number class",
"self.newPath = os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def",
"TER'S \"\"\" count = 0 with open(pdb, 'r') as x:",
"count += 1 if i.split()[3] == resname: molecule_number = count",
"os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self, etype,",
"changing the current working directory\"\"\" def __init__(self, newPath): self.newPath =",
"THE TER'S \"\"\" count = 0 with open(pdb, 'r') as",
"break return molecule_number class cd: \"\"\"Context manager for changing the",
"<gh_stars>1-10 import os def retrieve_molecule_number(pdb, resname): \"\"\" IDENTIFICATION OF MOLECULE",
"i in lines: if i.split()[0] == 'TER': count += 1",
"lines: if i.split()[0] == 'TER': count += 1 if i.split()[3]",
"== 'TER': count += 1 if i.split()[3] == resname: molecule_number",
"= os.path.expanduser(newPath) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPath) def __exit__(self,",
"molecule_number class cd: \"\"\"Context manager for changing the current working",
"IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S \"\"\" count",
"working directory\"\"\" def __init__(self, newPath): self.newPath = os.path.expanduser(newPath) def __enter__(self):",
"resname): \"\"\" IDENTIFICATION OF MOLECULE NUMBER BASED ON THE TER'S",
"import os def retrieve_molecule_number(pdb, resname): \"\"\" IDENTIFICATION OF MOLECULE NUMBER"
] |
[
"MIT License # # Beaglebone platform API file. from bbio.platform.platform",
"file. from bbio.platform.platform import detect_platform PLATFORM = detect_platform() if \"3.8\"",
"serial_cleanup def platform_init(): analog_init() pwm_init() def platform_cleanup(): analog_cleanup() pwm_cleanup() serial_cleanup()",
"# Beaglebone platform API file. from bbio.platform.platform import detect_platform PLATFORM",
"API file. from bbio.platform.platform import detect_platform PLATFORM = detect_platform() if",
"PLATFORM = detect_platform() if \"3.8\" in PLATFORM: from bone_3_8.adc import",
"serial_cleanup elif \"3.2\" in PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup",
"bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup def platform_init():",
"Part of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License # #",
"import serial_cleanup elif \"3.2\" in PLATFORM: from bone_3_2.adc import analog_init,",
"analog_init, analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port import",
"bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup from",
"pwm_init, pwm_cleanup from serial_port import serial_cleanup def platform_init(): analog_init() pwm_init()",
"PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm import pwm_init,",
"from bbio.platform.platform import detect_platform PLATFORM = detect_platform() if \"3.8\" in",
"serial_port import serial_cleanup elif \"3.2\" in PLATFORM: from bone_3_2.adc import",
"analog_init, analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port import",
"\"3.8\" in PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm",
"License # # Beaglebone platform API file. from bbio.platform.platform import",
"import pwm_init, pwm_cleanup from serial_port import serial_cleanup def platform_init(): analog_init()",
"# # Beaglebone platform API file. from bbio.platform.platform import detect_platform",
"# api.py # Part of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT",
"import serial_cleanup def platform_init(): analog_init() pwm_init() def platform_cleanup(): analog_cleanup() pwm_cleanup()",
"analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup",
"of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License # # Beaglebone",
"PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License # # Beaglebone platform",
"detect_platform PLATFORM = detect_platform() if \"3.8\" in PLATFORM: from bone_3_8.adc",
"from bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup",
"from serial_port import serial_cleanup def platform_init(): analog_init() pwm_init() def platform_cleanup():",
"from serial_port import serial_cleanup elif \"3.2\" in PLATFORM: from bone_3_2.adc",
"from bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup def",
"\"3.2\" in PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm",
"from bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup",
"github.com/alexanderhiam/PyBBIO # MIT License # # Beaglebone platform API file.",
"if \"3.8\" in PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup from",
"platform API file. from bbio.platform.platform import detect_platform PLATFORM = detect_platform()",
"= detect_platform() if \"3.8\" in PLATFORM: from bone_3_8.adc import analog_init,",
"in PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm import",
"detect_platform() if \"3.8\" in PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup",
"Beaglebone platform API file. from bbio.platform.platform import detect_platform PLATFORM =",
"analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup",
"pwm_cleanup from serial_port import serial_cleanup elif \"3.2\" in PLATFORM: from",
"# MIT License # # Beaglebone platform API file. from",
"PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup from bone_3_2.pwm import pwm_init,",
"pwm_cleanup from serial_port import serial_cleanup def platform_init(): analog_init() pwm_init() def",
"serial_port import serial_cleanup def platform_init(): analog_init() pwm_init() def platform_cleanup(): analog_cleanup()",
"elif \"3.2\" in PLATFORM: from bone_3_2.adc import analog_init, analog_cleanup from",
"api.py # Part of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License",
"in PLATFORM: from bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm import",
"import analog_init, analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port",
"import detect_platform PLATFORM = detect_platform() if \"3.8\" in PLATFORM: from",
"bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup elif \"3.2\"",
"import pwm_init, pwm_cleanup from serial_port import serial_cleanup elif \"3.2\" in",
"bone_3_8.adc import analog_init, analog_cleanup from bone_3_8.pwm import pwm_init, pwm_cleanup from",
"import analog_init, analog_cleanup from bone_3_2.pwm import pwm_init, pwm_cleanup from serial_port",
"from bone_3_8.pwm import pwm_init, pwm_cleanup from serial_port import serial_cleanup elif",
"bbio.platform.platform import detect_platform PLATFORM = detect_platform() if \"3.8\" in PLATFORM:",
"# Part of PyBBIO # github.com/alexanderhiam/PyBBIO # MIT License #",
"# github.com/alexanderhiam/PyBBIO # MIT License # # Beaglebone platform API",
"pwm_init, pwm_cleanup from serial_port import serial_cleanup elif \"3.2\" in PLATFORM:"
] |
[
"**parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters)",
"**attrs): return self.request(RouteList.get_vpn_info(), **attrs) # * VM def get_machine_running(self, **attrs):",
". import checks from .cog import request_cog GET='get' POST='post' class",
"path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room(",
"return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs):",
"paths def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters):",
"Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters) def",
"} if 'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] =",
"self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self,",
"get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters)",
"get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code, **attrs):",
"# ? rename to user profile def get_user_exist( **parameters): return",
"return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs)",
"try: with session.request(method, endpoint, **kwargs) as r: data = utils.response_to_json_or_text(r)",
"**parameters) def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters):",
"# * user -notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def",
"Leaderboards def get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type),",
"**attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs) # *",
"**parameters) def post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters):",
"False return None def request(self, route, **kwargs): session = self.__session",
"self.retrieve_CSRF_token() self.username = self.retrieve_username() except Exception as e: print(\"session Issue:\",",
"self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def",
"= None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if",
"e: raise e class Route: # TODO: add post payload",
"**parameters): return Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters)",
"get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs): return",
"self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards def get_leaderboards(self, country: _county_types, type:_leaderboard_types,",
"Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms(",
"get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\",",
"return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return",
"!= None]) self.bucket = f\"{method} {path}\" class RouteList: def get_profile_page(**parameters):",
"**attrs): return self.request(RouteList.get_all_notifications(), **attrs) # * user -messages @checks.is_authenticated() def",
"session=None): self._state = None self.authenticated = False self.__session = requests.Session()",
"+ \"&\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i]",
"path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient): # * normal site calls",
"self.BASE + self.path except Exception as e: raise errors.NotValidUrlParameters(e) else:",
"Route(path=\"/vpn/my-data\", **parameters) # * VM def get_machine_running( **parameters): return Route(path=\"/api/vm/running\",",
"def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\",",
"path='', **parameters): self.method = method self._path = path self.path =",
"return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) # *",
"@checks.is_authenticated() def post_leave_room(self, room_code, **attrs): return self.request(RouteList.post_leave_room(), json={\"code\": room_code}, **attrs)",
"user -team @checks.is_authenticated() def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs) #",
"Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is not None: self.static_login(session) def close(self):",
"country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # *",
"room def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self,",
"**attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self,",
"return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs)",
"**attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs)",
"* normal site calls def get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters)",
"get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\",",
"\"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs):",
"path=\"/api/vm/terminate\", **parameters) # * user -badge def get_own_badges( **parameters): return",
"options: if \"?\" not in self.url: self.url + \"?\" +",
"errors, utils from .converters import _county_types, _leaderboard_types, _vpn_types, _not_none from",
"$ no auth if r.status_code in {401, 403}: raise errors.Unauthorized(request=r,",
"return Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ? might be different for",
"return self.request(RouteList.get_all_badges(), **attrs) # * user -team @checks.is_authenticated() def get_team_info(self,",
"if not self.authenticated: return None try: page = self.request(RouteList.get_profile_page()) return",
"self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self,",
"**attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(),",
"quote as _uriquote import requests from . import __version__, errors,",
"capabilities BASE = \"https://www.tryhackme.com\" def __init__(self, method=GET, path='', **parameters): self.method",
"**attrs) def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards",
"is not None: self.static_login(session) def close(self): if self.__session: self.__session.close() def",
"**attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs)",
"**parameters) def get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters):",
"if r.status_code in {401, 403}: raise errors.Unauthorized(request=r, route=route, data=data) #",
"**parameters) def get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters):",
"**parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters)",
"= session cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications())",
"username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(),",
"**attrs): return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs)",
"**parameters): return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def",
"**parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters)",
"**attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(),",
"calls def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs):",
"None def retrieve_username(self): if not self.authenticated: return None try: page",
"**parameters) def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) # * user",
"**parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters): return",
"Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details(",
"no auth if r.status_code in {401, 403}: raise errors.Unauthorized(request=r, route=route,",
"Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ? might be different for premium",
"games def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters):",
": _not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs) # * room def",
"**parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters): return",
"**attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def",
"\"https://www.tryhackme.com\" def __init__(self, method=GET, path='', **parameters): self.method = method self._path",
"it gets stuff def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def",
"# * networks def get_networks( **parameters): return Route(path=\"/api/networks\", **parameters) def",
"post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters): return",
"try: self.path = self.path.format(**{k: _uriquote(v) if isinstance(v, str) else v",
"@checks.is_authenticated() def get_available_vpns(self, type : _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}),",
"**attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(),",
"return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) #",
"as e: raise e class Route: # TODO: add post",
"headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\" in settings:",
"self.path.format(**{k: _uriquote(v) if isinstance(v, str) else v for k, v",
"None) if parameters: try: self.path = self.path.format(**{k: _uriquote(v) if isinstance(v,",
"def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename to user",
"**attrs): return self.request(RouteList.get_subscription_cost(), **attrs) # * paths def get_path(self, path_code,",
"return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters) #",
"\"page\": page}), **attrs) # * user def get_user_rank(self, username :",
"utils from .converters import _county_types, _leaderboard_types, _vpn_types, _not_none from .",
"\"static\" in settings: session = self.static_session if \"CSRF\" in settings:",
"path=\"/games/koth/join-public\", **parameters) # ? might be different for premium users",
"modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def get_module( **parameters): return",
"post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs) # * VPN @checks.is_authenticated() def",
"is a post but it gets stuff def get_room_scoreboard( **parameters):",
"**parameters): return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def",
"str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\": answer},",
"# * user -team @checks.is_authenticated() def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(),",
"get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\":",
"self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self,",
"path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters) #",
"**parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) # * room def get_new_rooms( **parameters):",
"return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id),",
"get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\",",
"options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self,",
"> r.status_code >= 200: # $ if return url is",
"user -team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) # * user",
"parameters.items()}) self.url = self.BASE + self.path except Exception as e:",
"**parameters) def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list",
"room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code, **attrs): return",
"* VM def get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine(",
"get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters)",
"self.request(RouteList.get_group_messages(group_id), **attrs) # * user -room def get_user_completed_rooms_count(self, username, **attrs):",
"get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters)",
"def get_networks( **parameters): return Route(path=\"/api/networks\", **parameters) def get_network( **parameters): return",
"-notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def",
"loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs)",
"return Route(path=\"/api/team/is-member\", **parameters) # * user -notifications def get_unseen_notifications(**parameters): return",
"not in self.url: self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\" for i",
"Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) # *",
"= self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO: retries, Pagenator try:",
"def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards def",
"return self.request(RouteList.search_user(username=username), **attrs) # * room def get_new_rooms(self, **attrs): return",
"def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs):",
"**attrs) def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show,",
"get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs):",
"def get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) # * user",
"* modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def get_module( **parameters):",
"self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # * networks def get_network(self, network_code, **attrs):",
"with session.request(method, endpoint, **kwargs) as r: data = utils.response_to_json_or_text(r) #",
"Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms(",
"# * user -team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) #",
"get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) #",
"**parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters)",
"* VPN @checks.is_authenticated() def get_available_vpns(self, type : _vpn_types, **attrs): return",
"kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\" in settings: session = self.static_session",
"search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) # * room def get_new_rooms(",
"_not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username : _not_none,",
"def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) # * networks def get_networks(",
"return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True,",
"**attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types,",
"**attrs): return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code),",
"**attrs) def get_serie(self, show, serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}),",
"**parameters): return Route(path=\"/api/networks\", **parameters) def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters)",
"for i in options.keys() if options[i] != None]) else: self.url",
"**attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code),",
"**attrs) # * user -team @checks.is_authenticated() def get_team_info(self, **attrs): return",
"if 404 == r.status_code: raise errors.NotFound(request=r, route=route, data=data) # $",
"page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) #",
"get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs): return",
"post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters): return",
"requests/{requests.__version__}' if session is not None: self.static_login(session) def close(self): if",
"def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # * games def get_machine_pool(",
"self.__session = requests.Session() self.static_session = requests.Session() self.connect_sid = None self._CSRF_token",
"None self.authenticated = False self.__session = requests.Session() self.static_session = requests.Session()",
"get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) # * user -notifications def get_unseen_notifications(**parameters):",
"return None def retrieve_username(self): if not self.authenticated: return None try:",
"errors.ServerError(request=r, route=route, data=data) except Exception as e: raise e class",
"return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def",
"return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends(",
"else v for k, v in parameters.items()}) self.url = self.BASE",
"return Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters)",
"def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code, **attrs):",
"**parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters) # * user -badge def",
"return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def get_series(self, show, **attrs): return",
"self.retrieve_username() except Exception as e: print(\"session Issue:\", e) def retrieve_CSRF_token(self):",
"**attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def",
"room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self,",
"urllib.parse import quote as _uriquote import requests from . import",
"self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated()",
"= { 'User-Agent': self.user_agent } if 'json' in kwargs: headers['Content-Type']",
"Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ?",
"in {500, 502}: raise errors.ServerError(request=r, route=route, data=data) except Exception as",
"self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self,",
"answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId, **attrs): return",
"utils.response_to_json_or_text(r) # * valid return if 300 > r.status_code >=",
"try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated =",
"server side issue's if r.status_code in {500, 502}: raise errors.ServerError(request=r,",
"in {401, 403}: raise errors.Unauthorized(request=r, route=route, data=data) # $ endpoint",
"return Route(path=\"/api/networks\", **parameters) def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def",
"]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self,",
"return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # * networks def get_network(self, network_code,",
"Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters):",
"**attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(),",
"get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs) # * VM def get_machine_running(self,",
"**attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs) # *",
"= False return None def retrieve_username(self): if not self.authenticated: return",
"self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username,",
"**parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def",
"**parameters): return Route(path=\"/notifications/get\", **parameters) # * user -messages def get_unseen_messages(",
"get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters): return Route(method=POST,",
"get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) # * user def get_user_rank(",
"**parameters) def get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters):",
"**parameters) # ? rename to user profile def get_user_exist( **parameters):",
"def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs) # * user -messages",
"get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters): return Route(path=\"/paths/summary\",",
"r.status_code in {401, 403}: raise errors.Unauthorized(request=r, route=route, data=data) # $",
"**parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters): return Route(method=POST,",
"data=data) # $ server side issue's if r.status_code in {500,",
"**attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) # * user -room def get_user_completed_rooms_count(self,",
"self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs) # *",
"i in options.keys() if options[i] != None]) else: self.url +",
"_uriquote import requests from . import __version__, errors, utils from",
"@checks.is_authenticated() def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username,",
"def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\",",
"data = utils.response_to_json_or_text(r) # * valid return if 300 >",
"def request(self, route, **kwargs): session = self.__session endpoint = route.url",
">= 200: # $ if return url is login then",
"taskNo: int, questionNo: int, answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\":",
"route, **kwargs): session = self.__session endpoint = route.url method =",
"page}), **attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username,",
"**attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(),",
"= self.static_session if \"CSRF\" in settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"]",
"**attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code, **attrs): return self.request(RouteList.post_leave_room(), json={\"code\":",
"def post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient):",
"'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if",
"self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated = False return None def request(self,",
"return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code, taskNo: int,",
"Route(path=\"/api/badges/get\", **parameters) # * user -team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\",",
"return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters) def",
"]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state = None self.authenticated = False",
"options.keys() if options[i] != None]) else: self.url + \"&\" +",
"_not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username : _not_none,",
"**attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show, serie_code, **attrs): return",
"POST='post' class HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex",
"self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs)",
"return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters) #",
"def static_login(self, session): self.connect_sid = session cookie = requests.cookies.create_cookie('connect.sid', session,",
"k, v in parameters.items()}) self.url = self.BASE + self.path except",
"cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated =",
"return Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient): # * normal",
"user -badge def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters):",
"**attrs) def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs):",
"**attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self, group_id, **attrs): return",
"Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list posibility def get_room_tasks( **parameters): return",
"# * paths def get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs)",
"user def get_user_rank(self, username : _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs)",
"path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters) class",
"self.request(RouteList.get_team_info(), **attrs) # * user -notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs):",
"page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated = False",
"Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters) def get_path_summary(",
"Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters) def",
"* paths def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths(",
"\"questionNo\": questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code,",
"get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) # * user -room def",
"= f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is not",
"def get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs):",
"room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs)",
"@checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code},",
"self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show, serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\":",
"if r.status_code in {500, 502}: raise errors.ServerError(request=r, route=route, data=data) except",
"+ self.path options = parameters.pop(\"options\", None) if parameters: try: self.path",
"def get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account",
"Issue:\", e) def retrieve_CSRF_token(self): if not self.authenticated: return None try:",
"path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters) #",
"@checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code, **attrs): return self.request(RouteList.post_leave_room(), json={\"code\": room_code},",
"__init__(self, session=None): self._state = None self.authenticated = False self.__session =",
"return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs)",
"**parameters) def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters):",
"**parameters) def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters):",
"= requests.Session() self.static_session = requests.Session() self.connect_sid = None self._CSRF_token =",
"# * user def get_user_rank(self, username : _not_none, **attrs): return",
"**attrs) # * user -room def get_user_completed_rooms_count(self, username, **attrs): return",
": _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username :",
"* room def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms(",
"def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list posibility",
"None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated",
"in settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO:",
"get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs): return",
"$ server side issue's if r.status_code in {500, 502}: raise",
"# TODO: add post payload capabilities BASE = \"https://www.tryhackme.com\" def",
"-team @checks.is_authenticated() def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs) # *",
"r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r, route=route, data=data) return data #",
"def search_user(self, username : _not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs) #",
"**parameters) def post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine(",
"import sys from urllib.parse import quote as _uriquote import requests",
"**parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters)",
"* user -messages @checks.is_authenticated() def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs)",
"\"page\": page}), **attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return",
"if options[i] != None]) self.bucket = f\"{method} {path}\" class RouteList:",
"return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters) def",
"def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters): return",
"# * account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) # *",
"\"loadUser\": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code),",
"bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps,",
"return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages(",
"else: self.url = url if options: if \"?\" not in",
"v in parameters.items()}) self.url = self.BASE + self.path except Exception",
"return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\",",
"* user -messages def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters) def",
"limit, \"page\": page}), **attrs) # * user def get_user_rank(self, username",
"Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages(",
"{__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is not None: self.static_login(session) def",
"def post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters) # * user",
"= re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[ ]{0,1}=[",
"from .cog import request_cog GET='get' POST='post' class HTTPClient: __CSRF_token_regex =",
"**attrs) def get_user_activty(self, username : _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs)",
"get_networks( **parameters): return Route(path=\"/api/networks\", **parameters) def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\",",
"@checks.is_authenticated() def post_room_answer(self, room_code, taskNo: int, questionNo: int, answer: str,",
"return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF()",
"get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\",",
"**parameters) def get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters) # * user",
"self.url = self.BASE + self.path except Exception as e: raise",
"is login then no auth if r.url.split('/')[-1] == \"login\": raise",
"return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username : _not_none, **attrs): return",
"@checks.is_authenticated() def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs) # * VM",
"user -room def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def",
"{}) def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated()",
"**parameters) def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters):",
"**parameters) # * networks def get_networks( **parameters): return Route(path=\"/api/networks\", **parameters)",
"**parameters): return Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards def get_leaderboards( **parameters):",
"@checks.is_authenticated() def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self,",
"Route(method=POST, path=\"/api/vm/terminate\", **parameters) # * user -badge def get_own_badges( **parameters):",
"= self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated = False return",
"**attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs)",
"_vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs):",
"200: # $ if return url is login then no",
"room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs):",
"endpoint = route.url method = route.method settings = kwargs.pop('settings', {})",
"return data # $ no auth if r.status_code in {401,",
"get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\",",
"Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters) def",
"requests from . import __version__, errors, utils from .converters import",
"_not_none from . import checks from .cog import request_cog GET='get'",
"**attrs) def get_discord_user(self, username : _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs)",
"self.authenticated = True self._CSRF_token = self.retrieve_CSRF_token() self.username = self.retrieve_username() except",
"self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs) #",
"class HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex =",
"loadCreators: bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\":",
"return self.request(RouteList.get_group_messages(group_id), **attrs) # * user -room def get_user_completed_rooms_count(self, username,",
"Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters):",
"@checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs)",
"post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) # *",
"networks def get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self,",
"i in options.keys() if options[i] != None]) self.bucket = f\"{method}",
"return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters)",
"* user -team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) # *",
"static_login(self, session): self.connect_sid = session cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com')",
"method = route.method settings = kwargs.pop('settings', {}) headers = {",
"Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename to user profile def get_user_exist(",
"* user -notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications(",
"self.url: self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys()",
"def get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self,",
"game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(),",
"as e: raise errors.NotValidUrlParameters(e) else: self.url = url if options:",
"def post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters):",
"session cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated",
"= self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated = False return",
"* networks def get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def",
"self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username : _not_none, **attrs): return self.request(RouteList.search_user(username=username),",
"**parameters) # * paths def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters)",
"**attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def get_series(self, show, **attrs):",
"return Route(path=\"/account/subscription/cost\", **parameters) # * paths def get_path( **parameters): return",
"* user -room def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs)",
"# $ server side issue's if r.status_code in {500, 502}:",
"get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps:",
"def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters): return Route(path=\"/api/friend/all\",",
"username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs): return",
"**parameters) def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters): return",
"get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account def get_subscription_cost(**parameters):",
"-messages @checks.is_authenticated() def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def",
"# * Leaderboards def get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return",
"taskNo, \"questionNo\": questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self,",
"request(self, route, **kwargs): session = self.__session endpoint = route.url method",
"parameters.pop(\"options\", None) if parameters: try: self.path = self.path.format(**{k: _uriquote(v) if",
"def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) # * user -room",
"def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs)",
"not found if 404 == r.status_code: raise errors.NotFound(request=r, route=route, data=data)",
"return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self,",
"url is login then no auth if r.url.split('/')[-1] == \"login\":",
"if 'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json'))",
"in settings: session = self.static_session if \"CSRF\" in settings: headers['CSRF-Token']",
"_county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # * networks",
"def close(self): if self.__session: self.__session.close() def static_login(self, session): self.connect_sid =",
"return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) #",
"# $ endpoint not found if 404 == r.status_code: raise",
"**attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(),",
"be different for premium users # * VPN def get_available_vpns(**parameters):",
"# * VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF()",
"**attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code, taskNo: int, questionNo: int,",
"for i in options.keys() if options[i] != None]) self.bucket =",
"**parameters): return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters)",
"Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games(",
"def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters): return",
"**attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\":",
"Route(path=\"/api/created-rooms/{username}\", **parameters) # * user def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\",",
"posibility def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters):",
"**attrs) def get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def",
"return Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename to user profile def",
"def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters): return",
": _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username :",
"json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def",
"def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs) # * paths def",
"return Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters) #",
"**parameters): return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\",",
"self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated = False return None def retrieve_username(self):",
"return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) # ?",
"**parameters) def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards",
"return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code,",
"= utils.to_json(kwargs.pop('json')) if \"static\" in settings: session = self.static_session if",
"def get_user_exist(self, username : _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def",
"self.request(RouteList.get_path_summary(), **attrs) # * modules def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(),",
"get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\",",
"= route.method settings = kwargs.pop('settings', {}) headers = { 'User-Agent':",
"**parameters): return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) #",
"**parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list posibility def get_room_tasks(",
"from urllib.parse import quote as _uriquote import requests from .",
"None]) else: self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\" for i in",
"sys from urllib.parse import quote as _uriquote import requests from",
"return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) def get_user_created_rooms(self, username,",
"Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\", **parameters)",
"page}), **attrs) # * user def get_user_rank(self, username : _not_none,",
"show, **attrs): return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(),",
"**parameters) def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters) # * VM",
"**parameters) def post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine(",
"**attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username : _not_none, **attrs):",
"self.username = None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}'",
"self.authenticated = False return None def retrieve_username(self): if not self.authenticated:",
"payload capabilities BASE = \"https://www.tryhackme.com\" def __init__(self, method=GET, path='', **parameters):",
"@checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self,",
"self._path = path self.path = path url = self.BASE +",
"def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\",",
"return Route(path=\"/notifications/get\", **parameters) # * user -messages def get_unseen_messages( **parameters):",
"**attrs) # * account @checks.is_authenticated() def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(),",
"return self.request(RouteList.get_team_info(), **attrs) # * user -notifications @checks.is_authenticated() def get_unseen_notifications(self,",
"room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps: bool=True,",
"class Route: # TODO: add post payload capabilities BASE =",
"]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None):",
"kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\" in",
"get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\",",
"# * Leaderboards def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters) def",
"Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters):",
"headers = { 'User-Agent': self.user_agent } if 'json' in kwargs:",
"= requests.Session() self.connect_sid = None self._CSRF_token = None self.username =",
"Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters):",
"normal site calls def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs) def",
"get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10,",
"uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF()",
"get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) #",
"= self.path.format(**{k: _uriquote(v) if isinstance(v, str) else v for k,",
"Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) # *",
"self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated()",
": _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self, **attrs):",
"return self.request(RouteList.post_new_koth(), **attrs) # * VPN @checks.is_authenticated() def get_available_vpns(self, type",
"**attrs): return self.request(RouteList.get_module(module_code), **attrs) # * games def get_machine_pool(self, **attrs):",
"{401, 403}: raise errors.Unauthorized(request=r, route=route, data=data) # $ endpoint not",
"self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO: retries, Pagenator try: with",
"**parameters) def get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters) # ?",
"return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters) def",
"# * valid return if 300 > r.status_code >= 200:",
"def get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters): return",
"**parameters) # * modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def",
"domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token = self.retrieve_CSRF_token()",
"Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games(",
"self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs): return",
"def get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated()",
"-messages def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters): return",
"get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account @checks.is_authenticated()",
"@checks.is_authenticated() def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self,",
"= f\"{method} {path}\" class RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters)",
"= True self._CSRF_token = self.retrieve_CSRF_token() self.username = self.retrieve_username() except Exception",
"def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs): return",
"self.url = url if options: if \"?\" not in self.url:",
"options={\"limit\": limit, \"page\": page}), **attrs) # * user def get_user_rank(self,",
"return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs) def",
"* user def get_user_rank(self, username : _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username),",
"username : _not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs) # * room",
"errors.Unauthorized(request=r, route=route, data=data) # $ endpoint not found if 404",
"def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs) # * user -notifications",
"**attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) # * user",
"self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs) #",
"raise errors.Unauthorized(request=r, route=route, data=data) return data # $ no auth",
"**parameters) def post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters) # *",
"**parameters): return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\",",
"as e: print(\"session Issue:\", e) def retrieve_CSRF_token(self): if not self.authenticated:",
"self.static_login(session) def close(self): if self.__session: self.__session.close() def static_login(self, session): self.connect_sid",
"@checks.is_authenticated() def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self,",
"return if 300 > r.status_code >= 200: # $ if",
"@checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code,",
"get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs) # * paths def get_path(self,",
"Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters)",
"self.authenticated: return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except",
"Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters):",
"* normal site calls def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs)",
"**attrs) # * user -notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs): return",
"self.path except Exception as e: raise errors.NotValidUrlParameters(e) else: self.url =",
"**attrs): return self.request(RouteList.post_new_koth(), **attrs) # * VPN @checks.is_authenticated() def get_available_vpns(self,",
"route=route, data=data) # $ endpoint not found if 404 ==",
"parameters: try: self.path = self.path.format(**{k: _uriquote(v) if isinstance(v, str) else",
"def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs): return",
"**attrs): return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code),",
"502}: raise errors.ServerError(request=r, route=route, data=data) except Exception as e: raise",
"**attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # * networks def get_network(self,",
"**attrs) def get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self,",
"try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token = self.retrieve_CSRF_token() self.username =",
"* user -notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs)",
"found if 404 == r.status_code: raise errors.NotFound(request=r, route=route, data=data) #",
"user def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return",
"return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {})",
"import requests from . import __version__, errors, utils from .converters",
"= None self.username = None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__})",
"def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs):",
"**parameters) def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters):",
"def post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) #",
"return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs)",
"**attrs) # * networks def get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code),",
"**parameters) # * user def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters)",
"\"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs): return",
"**attrs) # * user -badge @checks.is_authenticated() def get_own_badges(self, **attrs): return",
"return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters) #",
"**attrs) # * room def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs)",
"# * user -room def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters)",
"return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def",
"e class Route: # TODO: add post payload capabilities BASE",
"= self.retrieve_CSRF_token() self.username = self.retrieve_username() except Exception as e: print(\"session",
"return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username : _not_none, **attrs): return",
"get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters)",
"def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) # * user -team",
"get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters)",
"def get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs):",
"self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username : _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username),",
"r.status_code: raise errors.NotFound(request=r, route=route, data=data) # $ server side issue's",
"@checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code, taskNo: int, questionNo: int, answer:",
"if session is not None: self.static_login(session) def close(self): if self.__session:",
"self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username : _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username),",
"@checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs)",
"serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def get_series(self, show,",
"def get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters): return",
"if parameters: try: self.path = self.path.format(**{k: _uriquote(v) if isinstance(v, str)",
"\"?\" not in self.url: self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\" for",
"def get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs) # * games",
"get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) # * networks def get_networks( **parameters):",
"username : _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username",
"close(self): if self.__session: self.__session.close() def static_login(self, session): self.connect_sid = session",
"return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(),",
"username : _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self, username",
"@checks.is_authenticated() def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs) # * user",
"* account @checks.is_authenticated() def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs) #",
"HTTPClient): # * normal site calls def get_server_time(self, **attrs): return",
"def __init__(self, session=None): self._state = None self.authenticated = False self.__session",
"# ? list posibility def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters)",
"**parameters): return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def",
"def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters): return Route(method=POST,",
"return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def",
"self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) # *",
"loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs): return",
"paths def get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self,",
"normal site calls def get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters) def",
"* user def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters):",
"* paths def get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def",
"Route(path=\"/api/networks\", **parameters) def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost(",
"= self.__session endpoint = route.url method = route.method settings =",
"-badge @checks.is_authenticated() def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self,",
"def get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters): return",
"self.authenticated: return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except",
"not self.authenticated: return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1)",
"get_user_activty(self, username : _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def",
"import checks from .cog import request_cog GET='get' POST='post' class HTTPClient:",
"page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated = False",
"self.method = method self._path = path self.path = path url",
"* user -badge @checks.is_authenticated() def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs)",
"return Route(path=\"/modules/summary\", **parameters) def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # *",
"post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters): return",
"page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) def",
"**parameters) # * user -badge def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\",",
"except AttributeError: self.authenticated = False return None def request(self, route,",
"session.request(method, endpoint, **kwargs) as r: data = utils.response_to_json_or_text(r) # *",
"limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs)",
"e: raise errors.NotValidUrlParameters(e) else: self.url = url if options: if",
"= self.BASE + self.path except Exception as e: raise errors.NotValidUrlParameters(e)",
"post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return Route(method=POST,",
"def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs):",
"post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient): #",
"get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username : _not_none,",
"Route(path=\"/api/leaderboards/koth\", **parameters) # * networks def get_networks( **parameters): return Route(path=\"/api/networks\",",
"endpoint not found if 404 == r.status_code: raise errors.NotFound(request=r, route=route,",
"None self.username = None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]}",
"loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\":",
"but it gets stuff def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters)",
"**parameters): return Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters)",
"get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards def get_leaderboards(",
"request_cog GET='get' POST='post' class HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[",
"raise e class Route: # TODO: add post payload capabilities",
"**parameters): return Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\",",
"get_discord_user(self, username : _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self,",
"username : _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self,",
"int, questionNo: int, answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo,",
"**attrs).get(room_code, {}) def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF()",
"retrieve_username(self): if not self.authenticated: return None try: page = self.request(RouteList.get_profile_page())",
"def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters): return",
"**attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def",
"class RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) # * normal",
"self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated = False return None",
"return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(),",
"Route(path=\"/modules/summary\", **parameters) def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # * games",
"# * games def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs) def",
"get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters)",
"get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username, **attrs): return",
"self._state = None self.authenticated = False self.__session = requests.Session() self.static_session",
"**parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters)",
"**attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) def get_user_created_rooms(self,",
"def get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters) # * user -team",
"def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) # * room def",
"return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(),",
"**attrs) def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username,",
"-room def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self,",
"return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def",
"utils.to_json(kwargs.pop('json')) if \"static\" in settings: session = self.static_session if \"CSRF\"",
"**parameters): return Route(path=\"/vpn/my-data\", **parameters) # * VM def get_machine_running( **parameters):",
"Route(path=\"/profile\", **parameters) # * normal site calls def get_server_time( **parameters):",
"**attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def",
"return url is login then no auth if r.url.split('/')[-1] ==",
"+ \"?\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i]",
"calls def get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters):",
"account @checks.is_authenticated() def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs) # *",
"**parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ? might be different",
": _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def get_vpn_info(self,",
"room_code, taskNo: int, questionNo: int, answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code),",
"TODO: retries, Pagenator try: with session.request(method, endpoint, **kwargs) as r:",
"Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters) # *",
"self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def",
"answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\":",
"in options.keys() if options[i] != None]) self.bucket = f\"{method} {path}\"",
"BASE = \"https://www.tryhackme.com\" def __init__(self, method=GET, path='', **parameters): self.method =",
"Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms(",
"\"login\": raise errors.Unauthorized(request=r, route=route, data=data) return data # $ no",
"+ self.path except Exception as e: raise errors.NotValidUrlParameters(e) else: self.url",
"**parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters): return Route(method=POST,",
"HTTP(request_cog, HTTPClient): # * normal site calls def get_server_time(self, **attrs):",
"get_available_vpns(self, type : _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated()",
"**parameters): return Route(path=\"/paths/summary\", **parameters) # * modules def get_modules_summary(**parameters): return",
"return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def",
"= False return None def request(self, route, **kwargs): session =",
"site calls def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self,",
"**attrs) def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True,",
"**attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code},",
"limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs)",
"retries, Pagenator try: with session.request(method, endpoint, **kwargs) as r: data",
"user -badge @checks.is_authenticated() def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs) def",
"def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) # * modules def",
"# * modules def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs) def",
"# * user -room def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username),",
"self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username : _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username),",
"* games def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail(",
"= False self.__session = requests.Session() self.static_session = requests.Session() self.connect_sid =",
"\"?\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i] !=",
"# * games def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def",
"'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\" in settings: session =",
"r.status_code >= 200: # $ if return url is login",
"return Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\",",
"requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token",
"def retrieve_username(self): if not self.authenticated: return None try: page =",
"get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\",",
"**attrs): return self.request(RouteList.search_user(username=username), **attrs) # * room def get_new_rooms(self, **attrs):",
"Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename",
"self.request(RouteList.get_all_notifications(), **attrs) # * user -messages @checks.is_authenticated() def get_unseen_messages(self, **attrs):",
"side issue's if r.status_code in {500, 502}: raise errors.ServerError(request=r, route=route,",
"AttributeError: self.authenticated = False return None def retrieve_username(self): if not",
"return Route(method=POST, path=\"/api/room-percentages\", **parameters) # ? is a post but",
"**parameters) # * user -room def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\",",
"self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def",
"import __version__, errors, utils from .converters import _county_types, _leaderboard_types, _vpn_types,",
"= self._CSRF_token # TODO: retries, Pagenator try: with session.request(method, endpoint,",
"post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ? might be",
"**attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code,",
"**attrs): return self.request(RouteList.get_team_info(), **attrs) # * user -notifications @checks.is_authenticated() def",
"-team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) # * user -notifications",
"None]) self.bucket = f\"{method} {path}\" class RouteList: def get_profile_page(**parameters): return",
"return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs)",
"return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError:",
"auth if r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r, route=route, data=data) return",
"**attrs): return self.request(RouteList.get_path_summary(), **attrs) # * modules def get_modules_summary(self, **attrs):",
"**attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs)",
"**attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def",
"Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters)",
"**parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # * games def get_machine_pool( **parameters): return",
"return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list posibility def get_room_tasks( **parameters):",
"@checks.is_authenticated() def get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) # *",
"username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}),",
"**parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters)",
"def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self, group_id,",
"300 > r.status_code >= 200: # $ if return url",
"**attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\": answer}, **attrs)",
"Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters) #",
"r: data = utils.response_to_json_or_text(r) # * valid return if 300",
".converters import _county_types, _leaderboard_types, _vpn_types, _not_none from . import checks",
"def post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters):",
"group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) # * user -room def",
"__version__, errors, utils from .converters import _county_types, _leaderboard_types, _vpn_types, _not_none",
"**parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters)",
"!= None]) else: self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\" for i",
"**parameters): return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters)",
"post_deploy_machine(self, room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId},",
"def get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters): return",
"user -room def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms(",
"? rename to user profile def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\",",
"**attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs)",
"no auth if r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r, route=route, data=data)",
"self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code, **attrs):",
"**attrs) # * user -messages @checks.is_authenticated() def get_unseen_messages(self, **attrs): return",
"**attrs) # * paths def get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code),",
"def get_user_activty(self, username : _not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated()",
"return Route(path=\"/paths/summary\", **parameters) # * modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\",",
"v for k, v in parameters.items()}) self.url = self.BASE +",
"def get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs):",
"get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\",",
"def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs): return",
"try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated =",
"get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self, group_id, **attrs):",
"post payload capabilities BASE = \"https://www.tryhackme.com\" def __init__(self, method=GET, path='',",
"@checks.is_authenticated() def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self,",
"**attrs) # * games def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs)",
"def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\",",
"* user -badge def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters) def",
"route.url method = route.method settings = kwargs.pop('settings', {}) headers =",
"**parameters): return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) #",
"self.bucket = f\"{method} {path}\" class RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\",",
"**parameters) # ? might be different for premium users #",
"**attrs) def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs):",
"-badge def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return",
"None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session",
"self.request(RouteList.search_user(username=username), **attrs) # * room def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(),",
"retrieve_CSRF_token(self): if not self.authenticated: return None try: page = self.request(RouteList.get_profile_page())",
"def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs) # * VPN @checks.is_authenticated()",
"* user -room def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def",
"\"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId, **attrs):",
"**attrs) def get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs) # *",
"def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account def",
"* user -team @checks.is_authenticated() def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs)",
"get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters) # * modules def get_modules_summary(**parameters):",
"return None def request(self, route, **kwargs): session = self.__session endpoint",
"return Route(path=\"/modules/data/{module_code}\",**parameters) # * games def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\",",
"**parameters) # * normal site calls def get_server_time( **parameters): return",
"? list posibility def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def",
"if \"CSRF\" in settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token",
"if options[i] != None]) else: self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\"",
"def get_user_completed_rooms_count(self, username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username,",
"**attrs) def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs):",
"session): self.connect_sid = session cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie)",
"# * user def get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def",
"**parameters) def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters):",
"__init__(self, method=GET, path='', **parameters): self.method = method self._path = path",
"self.path = self.path.format(**{k: _uriquote(v) if isinstance(v, str) else v for",
"**parameters) def get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters) # * modules",
"return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth(",
"bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators,",
"_leaderboard_types, _vpn_types, _not_none from . import checks from .cog import",
"**attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account @checks.is_authenticated() def get_subscription_cost(self,",
"raise errors.Unauthorized(request=r, route=route, data=data) # $ endpoint not found if",
"def post_deploy_machine(self, room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\":",
"loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\":",
"room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def",
"network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account @checks.is_authenticated() def",
"return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters)",
"get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters): return Route(path=\"/api/series?show={show}\",",
"self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code,",
"if 300 > r.status_code >= 200: # $ if return",
"raise errors.NotValidUrlParameters(e) else: self.url = url if options: if \"?\"",
"self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is",
"as _uriquote import requests from . import __version__, errors, utils",
"Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\",",
"self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) # *",
"def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs): return",
"def get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes,",
"get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters): return Route(path=\"/paths/public\",",
"Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) # * networks",
"# * account @checks.is_authenticated() def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs)",
"**parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters)",
"data=data) except Exception as e: raise e class Route: #",
"def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code,",
"json={\"roomCode\": room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code,",
"= requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True",
"**attrs) # * VPN @checks.is_authenticated() def get_available_vpns(self, type : _vpn_types,",
"json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code),",
"errors.Unauthorized(request=r, route=route, data=data) return data # $ no auth if",
"def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges( **parameters): return Route(path=\"/api/badges/get\",",
"return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs): return self.request(RouteList.get_all_group_messages(), **attrs)",
"**parameters): return Route(path=\"/api/badges/get\", **parameters) # * user -team def get_team_info(**parameters):",
"return Route(path=\"/api/badges/get\", **parameters) # * user -team def get_team_info(**parameters): return",
"get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters)",
"get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs) # * user -notifications @checks.is_authenticated()",
"def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self, **attrs):",
"in self.url: self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\" for i in",
"username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}),",
"def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters): return Route(path=\"/notifications/get\",",
"def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs): return",
"**parameters) def search_user( **parameters): return Route(path=\"/api/similar-users/{username}\", **parameters) # * room",
"Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters) # *",
"**attrs) # * modules def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs)",
"def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs):",
"= method self._path = path self.path = path url =",
"errors.NotValidUrlParameters(e) else: self.url = url if options: if \"?\" not",
"get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\",",
"**parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters) # ? is a post",
"**parameters): return Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters)",
"Route(path=\"/modules/data/{module_code}\",**parameters) # * games def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters)",
"if r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r, route=route, data=data) return data",
"**attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs): return",
"return Route(path=\"/api/similar-users/{username}\", **parameters) # * room def get_new_rooms( **parameters): return",
"requests.Session() self.static_session = requests.Session() self.connect_sid = None self._CSRF_token = None",
"premium users # * VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters)",
"def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code, **attrs):",
"self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs): return",
"None def request(self, route, **kwargs): session = self.__session endpoint =",
"@checks.is_authenticated() def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username",
"**parameters) def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters):",
"def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username, **attrs):",
"def post_room_answer(self, room_code, taskNo: int, questionNo: int, answer: str, **attrs):",
"_county_types, _leaderboard_types, _vpn_types, _not_none from . import checks from .cog",
"return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) #",
"get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs) # * user -messages @checks.is_authenticated()",
"self.request(RouteList.get_vpn_info(), **attrs) # * VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(),",
"def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters): return",
"return Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\",",
"def get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters): return",
"**parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\",",
"get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code, **attrs): return",
"return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated()",
"= path url = self.BASE + self.path options = parameters.pop(\"options\",",
"def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code,",
"search_user(self, username : _not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs) # *",
"return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show, serie_code, **attrs): return self.request(RouteList.get_series(show=show,",
"@checks.is_authenticated() def get_team_info(self, **attrs): return self.request(RouteList.get_team_info(), **attrs) # * user",
"account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) # * paths def",
"return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters) #",
"self.request(RouteList.get_subscription_cost(), **attrs) # * paths def get_path(self, path_code, **attrs): return",
"networks def get_networks( **parameters): return Route(path=\"/api/networks\", **parameters) def get_network( **parameters):",
"headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO: retries, Pagenator",
"return Route(path=\"/profile\", **parameters) # * normal site calls def get_server_time(",
"self.path = path url = self.BASE + self.path options =",
"get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) # * modules def get_modules_summary(self,",
"# * user -messages def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters)",
"**attrs): return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(), **attrs)",
"valid return if 300 > r.status_code >= 200: # $",
"@checks.set_header_CSRF() def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self,",
"**attrs): return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username),",
"re import sys from urllib.parse import quote as _uriquote import",
"Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient): # * normal site",
"return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError: self.authenticated = False return None def",
"def get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters) # * modules def",
": _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username :",
"site calls def get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters) def get_site_stats(",
"def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show, serie_code,",
"def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters): return",
"modules def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code,",
"_vpn_types, _not_none from . import checks from .cog import request_cog",
"**parameters) def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return",
"# * normal site calls def get_server_time( **parameters): return Route(path=\"/api/server-time\",",
"profile def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters):",
"get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs): return",
"# * room def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated()",
"= path self.path = path url = self.BASE + self.path",
"TODO: add post payload capabilities BASE = \"https://www.tryhackme.com\" def __init__(self,",
"**parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters)",
"if options: if \"?\" not in self.url: self.url + \"?\"",
"if return url is login then no auth if r.url.split('/')[-1]",
"route=route, data=data) except Exception as e: raise e class Route:",
"return Route(path=\"/message/group/get/{group_id}\", **parameters) # * user -room def get_user_completed_rooms_count( **parameters):",
"if \"?\" not in self.url: self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\"",
"f\"{method} {path}\" class RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) #",
"get_machine_pool( **parameters): return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\",",
"def get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\",",
"add post payload capabilities BASE = \"https://www.tryhackme.com\" def __init__(self, method=GET,",
"self._CSRF_token = None self.username = None self.user_agent = f'Tryhackme: (https://github.com/GnarLito/thm-api-py",
"questionNo: int, answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\":",
"403}: raise errors.Unauthorized(request=r, route=route, data=data) # $ endpoint not found",
"**parameters): self.method = method self._path = path self.path = path",
"Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters):",
"return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) #",
"return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\",",
"not self.authenticated: return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1)",
"else: self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys()",
"**parameters) # * Leaderboards def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters)",
"self.__session endpoint = route.url method = route.method settings = kwargs.pop('settings',",
"\"CSRF\" in settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token #",
"def get_serie(self, show, serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs)",
"**attrs): return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs)",
"self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated = False return None",
"get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters) # * user -messages def",
"get_user_rank( **parameters): return Route(path=\"/api/user/rank/{username}\", **parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters)",
"checks from .cog import request_cog GET='get' POST='post' class HTTPClient: __CSRF_token_regex",
"def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters): return",
"self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser:",
"settings: session = self.static_session if \"CSRF\" in settings: headers['CSRF-Token'] =",
"**attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) # *",
"def __init__(self, method=GET, path='', **parameters): self.method = method self._path =",
"method self._path = path self.path = path url = self.BASE",
"# * networks def get_network(self, network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs)",
"get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\":",
"room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self,",
"**attrs) # * Leaderboards def get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs):",
"self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF()",
"\"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i] != None]) self.bucket",
"return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs) def",
"**attrs): return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username : _not_none, **attrs):",
"not None: self.static_login(session) def close(self): if self.__session: self.__session.close() def static_login(self,",
"get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters) # ? is a",
"False return None def retrieve_username(self): if not self.authenticated: return None",
"return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) # * user",
"\"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i] != None]) else:",
"return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) #",
"Exception as e: raise errors.NotValidUrlParameters(e) else: self.url = url if",
"RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) # * normal site",
"**parameters) def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) # * user",
"endpoint, **kwargs) as r: data = utils.response_to_json_or_text(r) # * valid",
"from . import __version__, errors, utils from .converters import _county_types,",
"post but it gets stuff def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\",",
"user -messages def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\", **parameters) def get_all_group_messages(**parameters):",
"return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) #",
"**attrs) @checks.is_authenticated() def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self,",
"def retrieve_CSRF_token(self): if not self.authenticated: return None try: page =",
"self.path options = parameters.pop(\"options\", None) if parameters: try: self.path =",
"return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs)",
"type=type), **attrs) def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(),",
"**attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code},",
"return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username : _not_none, **attrs): return",
"get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters)",
"**parameters) # * user -team def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters)",
"room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code,",
"get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(),",
"_not_none, **attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self, **attrs): return",
"def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs):",
"**parameters) def get_all_friends( **parameters): return Route(path=\"/api/friend/all\", **parameters) def get_discord_user(**parameters): return",
"'User-Agent': self.user_agent } if 'json' in kwargs: headers['Content-Type'] = 'application/json'",
"* valid return if 300 > r.status_code >= 200: #",
"return self.request(RouteList.get_module(module_code), **attrs) # * games def get_machine_pool(self, **attrs): return",
"questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId,",
"def get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters) # * user -messages",
"from .converters import _county_types, _leaderboard_types, _vpn_types, _not_none from . import",
"return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated = False return None def",
"to user profile def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def",
"auth if r.status_code in {401, 403}: raise errors.Unauthorized(request=r, route=route, data=data)",
"**parameters) def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters):",
"**attrs) def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type),",
"get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\",",
"options = parameters.pop(\"options\", None) if parameters: try: self.path = self.path.format(**{k:",
"_uriquote(v) if isinstance(v, str) else v for k, v in",
".cog import request_cog GET='get' POST='post' class HTTPClient: __CSRF_token_regex = re.compile(\"const",
"get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters) def post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\",",
"@checks.is_authenticated() def get_subscription_cost(self, **attrs): return self.request(RouteList.get_subscription_cost(), **attrs) # * paths",
"= 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\" in settings: session",
"= self.BASE + self.path options = parameters.pop(\"options\", None) if parameters:",
"? is a post but it gets stuff def get_room_scoreboard(",
"self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\":",
"different for premium users # * VPN def get_available_vpns(**parameters): return",
"def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit,",
"# $ if return url is login then no auth",
"= url if options: if \"?\" not in self.url: self.url",
"def post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\", **parameters) def post_reset_room_progress(**parameters): return",
"**parameters) def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters):",
"Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered(",
"return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username : _not_none, **attrs): return",
"Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # *",
"in options.keys() if options[i] != None]) else: self.url + \"&\"",
"room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code,",
"def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters): return",
"import request_cog GET='get' POST='post' class HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[",
"username, **attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1,",
"return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs)",
"get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) # * paths def get_path( **parameters):",
"import quote as _uriquote import requests from . import __version__,",
"path url = self.BASE + self.path options = parameters.pop(\"options\", None)",
"if isinstance(v, str) else v for k, v in parameters.items()})",
"Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters): return Route(path=\"/notifications/get\", **parameters) # *",
"self.__session: self.__session.close() def static_login(self, session): self.connect_sid = session cookie =",
"get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) # * normal site calls def",
"rename to user profile def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters)",
"@checks.is_authenticated() def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs):",
"# * VM def get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters) def",
"**attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self,",
"Exception as e: print(\"session Issue:\", e) def retrieve_CSRF_token(self): if not",
"# ? might be different for premium users # *",
"get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def",
"Leaderboards def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters): return",
"serie_code}), **attrs) def get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show), **attrs) def",
"__CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[",
"get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\",",
"Route(path=\"/paths/public\", **parameters) def get_path_summary( **parameters): return Route(path=\"/paths/summary\", **parameters) # *",
"**parameters) # ? is a post but it gets stuff",
"route.method settings = kwargs.pop('settings', {}) headers = { 'User-Agent': self.user_agent",
"def post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF()",
"self.request(RouteList.get_user_created_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) # * user def",
"raise errors.ServerError(request=r, route=route, data=data) except Exception as e: raise e",
"self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self,",
"**attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\":",
"**attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\":",
"return self.request(RouteList.get_path_summary(), **attrs) # * modules def get_modules_summary(self, **attrs): return",
"def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters)",
"return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs) def",
"def get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def",
"issue's if r.status_code in {500, 502}: raise errors.ServerError(request=r, route=route, data=data)",
"class HTTP(request_cog, HTTPClient): # * normal site calls def get_server_time(self,",
"**parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def get_public_paths( **parameters): return Route(path=\"/paths/public\", **parameters)",
"**parameters) # * room def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters)",
"def get_path(self, path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs):",
"options={\"limit\": limit, \"page\": page}), **attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1,",
"{ 'User-Agent': self.user_agent } if 'json' in kwargs: headers['Content-Type'] =",
"then no auth if r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r, route=route,",
"return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters)",
"data # $ no auth if r.status_code in {401, 403}:",
"**attrs) def get_room_votes(self, room_code, **attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self,",
"get_room_tasks(self, room_code, **attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self,",
"get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators: bool=True, loadUser: bool=True, **attrs): return",
"# ? is a post but it gets stuff def",
"session is not None: self.static_login(session) def close(self): if self.__session: self.__session.close()",
"get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated() def get_all_group_messages(self, **attrs): return",
"e) def retrieve_CSRF_token(self): if not self.authenticated: return None try: page",
"{}) headers = { 'User-Agent': self.user_agent } if 'json' in",
"get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters): return Route(method=POST,",
"get_server_time(self, **attrs): return self.request(RouteList.get_server_time(), **attrs) def get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(),",
"self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return",
"self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def",
"post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def",
"print(\"session Issue:\", e) def retrieve_CSRF_token(self): if not self.authenticated: return None",
"return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) #",
"**parameters): return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters)",
"return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs)",
"# * normal site calls def get_server_time(self, **attrs): return self.request(RouteList.get_server_time(),",
"get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename to user profile",
"self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo, \"answer\": answer}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated()",
"**kwargs) as r: data = utils.response_to_json_or_text(r) # * valid return",
"get_recommended_rooms(self, **attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(),",
"def post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ? might",
"isinstance(v, str) else v for k, v in parameters.items()}) self.url",
"get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self, **attrs): return",
"# * VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info(",
"return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def",
"VPN @checks.is_authenticated() def get_available_vpns(self, type : _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\":",
"might be different for premium users # * VPN def",
"self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs) #",
"as r: data = utils.response_to_json_or_text(r) # * valid return if",
"settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO: retries,",
"return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs)",
"import re import sys from urllib.parse import quote as _uriquote",
"self.request(RouteList.post_new_koth(), **attrs) # * VPN @checks.is_authenticated() def get_available_vpns(self, type :",
"self._CSRF_token # TODO: retries, Pagenator try: with session.request(method, endpoint, **kwargs)",
"type=type), **attrs) # * networks def get_network(self, network_code, **attrs): return",
"{path}\" class RouteList: def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) # *",
"get_room_details( **parameters): return Route(path=\"/api/room/details?codes={room_code}\", **parameters) # ? list posibility def",
"type}), **attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs) #",
"self.authenticated = False self.__session = requests.Session() self.static_session = requests.Session() self.connect_sid",
"def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs) def get_discord_user(self, username :",
"options.keys() if options[i] != None]) self.bucket = f\"{method} {path}\" class",
"**attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username : _not_none, **attrs):",
"Route(method=POST, path=\"/api/room-percentages\", **parameters) # ? is a post but it",
"# * user -badge @checks.is_authenticated() def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(),",
"**attrs) # * VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs)",
"def get_questions_answered( **parameters): return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters): return",
"self.connect_sid = session cookie = requests.cookies.create_cookie('connect.sid', session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try:",
"Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters): return Route(method=POST, path=\"/api/{room_code}/answer\", **parameters) def",
"self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token = self.retrieve_CSRF_token() self.username",
"get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def get_recommended_rooms(self, **attrs): return",
"self.username = self.retrieve_username() except Exception as e: print(\"session Issue:\", e)",
"user -notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated()",
"get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username, **attrs): return",
"self.request(RouteList.get_all_group_messages(), **attrs) @checks.is_authenticated() def get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs)",
"**attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username : _not_none, **attrs):",
"def get_team_info(**parameters): return Route(path=\"/api/team/is-member\", **parameters) # * user -notifications def",
"@checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs)",
"requests.Session() self.connect_sid = None self._CSRF_token = None self.username = None",
"url if options: if \"?\" not in self.url: self.url +",
"get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters) # * user -team def",
"Route(path=\"/api/team/is-member\", **parameters) # * user -notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\",",
"$ if return url is login then no auth if",
"**attrs): return self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards def get_leaderboards(self, country:",
"# * user -messages @checks.is_authenticated() def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(),",
"* modules def get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self,",
"def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs):",
"# * room def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters) def",
"def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters) # * VM def",
"def post_renew_machine( **parameters): return Route(method=POST, path=\"/api/vm/renew\", **parameters) def post_terminate_machine( **parameters):",
"def get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs)",
"GET='get' POST='post' class HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\")",
"def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return",
"list posibility def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer(",
"json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code, **attrs): return",
"self.user_agent } if 'json' in kwargs: headers['Content-Type'] = 'application/json' kwargs['data']",
"self.static_session if \"CSRF\" in settings: headers['CSRF-Token'] = self._CSRF_token kwargs[\"data\"][\"_CSRF\"] =",
"session = self.static_session if \"CSRF\" in settings: headers['CSRF-Token'] = self._CSRF_token",
"return self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account @checks.is_authenticated() def get_subscription_cost(self, **attrs):",
"return Route(path=\"/api/questions-answered\", **parameters) def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters) def",
"return Route(path=\"/vpn/my-data\", **parameters) # * VM def get_machine_running( **parameters): return",
"VM def get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters):",
"get_all_badges(self, **attrs): return self.request(RouteList.get_all_badges(), **attrs) # * user -team @checks.is_authenticated()",
"return None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__Username_regex.search(page).group(1) except AttributeError:",
"_county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self, country:",
"get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters): return Route(path=\"/api/site-stats\",",
"**attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code,",
"Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters): return Route(path=\"/api/all-completed-rooms?username={username}\", **parameters) def get_user_created_rooms(",
"Pagenator try: with session.request(method, endpoint, **kwargs) as r: data =",
"return Route(path=\"/api/created-rooms/{username}\", **parameters) # * user def get_user_rank( **parameters): return",
"json={\"code\": room_code}, **attrs) # * user -badge @checks.is_authenticated() def get_own_badges(self,",
"get_site_stats(self, **attrs): return self.request(RouteList.get_site_stats(), **attrs) def get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(),",
"get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards def get_leaderboards(self,",
"country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self,",
"**attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(), **attrs) # *",
"**attrs): return self.request(RouteList.get_room_votes(room_code=room_code), **attrs) def get_room_details(self, room_code, loadWriteUps: bool=True, loadCreators:",
"def get_vpn_info(self, **attrs): return self.request(RouteList.get_vpn_info(), **attrs) # * VM def",
"Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters)",
"* games def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self,",
"**parameters) # * user -notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters)",
"# * user -notifications @checks.is_authenticated() def get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(),",
"return self.request(RouteList.get_vpn_info(), **attrs) # * VM def get_machine_running(self, **attrs): return",
"self.request(RouteList.get_module(module_code), **attrs) # * games def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(),",
"**attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) # * user -badge",
"return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code, **attrs):",
"return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs)",
"# * modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters) def get_module(",
"def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters): return",
"path self.path = path url = self.BASE + self.path options",
"url = self.BASE + self.path options = parameters.pop(\"options\", None) if",
"session, domain='tryhackme.com') self.__session.cookies.set_cookie(cookie) try: self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token =",
"self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code, taskNo: int, questionNo:",
"options[i] != None]) else: self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\" for",
"**attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes},",
"= utils.response_to_json_or_text(r) # * valid return if 300 > r.status_code",
"a post but it gets stuff def get_room_scoreboard( **parameters): return",
"**attrs): return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs)",
"get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters) def post_renew_machine( **parameters): return Route(method=POST,",
"kwargs.pop('settings', {}) headers = { 'User-Agent': self.user_agent } if 'json'",
"self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) # * user -badge @checks.is_authenticated() def",
"login then no auth if r.url.split('/')[-1] == \"login\": raise errors.Unauthorized(request=r,",
"gets stuff def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes(",
"+ \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i] != None])",
"return Route(path=\"/api/leaderboards/koth\", **parameters) # * networks def get_networks( **parameters): return",
"get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # * games def get_machine_pool( **parameters):",
"get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code),",
"f'Tryhackme: (https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is not None:",
"options={\"name\": serie_code}), **attrs) def get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show), **attrs)",
"csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def",
"= \"https://www.tryhackme.com\" def __init__(self, method=GET, path='', **parameters): self.method = method",
"return Route(path=\"/games/koth/get/machine-pool\", **parameters) def get_game_detail( **parameters): return Route(path=\"/games/koth/data/{game_code}\", **parameters) def",
"get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs):",
"if self.__session: self.__session.close() def static_login(self, session): self.connect_sid = session cookie",
"return self.request(RouteList.get_all_notifications(), **attrs) # * user -messages @checks.is_authenticated() def get_unseen_messages(self,",
"**attrs) def search_user(self, username : _not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs)",
"except AttributeError: self.authenticated = False return None def retrieve_username(self): if",
"* VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def",
"network_code, **attrs): return self.request(RouteList.get_network(network_code=network_code), **attrs) def get_networks(self, **attrs): return self.request(RouteList.get_networks(),**attrs)",
"return Route(path=\"/api/practice-rooms\", **parameters) def get_series( **parameters): return Route(path=\"/api/series?show={show}\", **parameters) def",
"# * user -badge def get_own_badges( **parameters): return Route(path=\"/api/badges/mine\", **parameters)",
"uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(),",
"username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state = None self.authenticated",
"**attrs) def get_user_badges(self, username, **attrs): return self.request(RouteList.get_user_badges(username=username), **attrs) def get_all_badges(self,",
"get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs): return",
"get_module(self, module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs) # * games def",
"**parameters) def get_user_activty(**parameters): return Route(path=\"/api/user/activity-events?username={username}\", **parameters) def get_all_friends( **parameters): return",
"def get_discord_user(self, username : _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def",
"def post_renew_machine(self, room_code, **attrs): return self.request(RouteList.post_renew_machine(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF()",
"return Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\",",
"**parameters) def get_koth_leaderboards(**parameters): return Route(path=\"/api/leaderboards/koth\", **parameters) # * networks def",
"get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def",
"get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters) # * VM def get_machine_running(",
"== \"login\": raise errors.Unauthorized(request=r, route=route, data=data) return data # $",
"? might be different for premium users # * VPN",
"def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\", **parameters) def post_room_answer( **parameters): return",
"**parameters): return Route(path=\"/api/series?show={show}\", **parameters) def get_glossary_terms( **parameters): return Route(path=\"/glossary/all-terms\", **parameters)",
"get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters)",
"# * VPN @checks.is_authenticated() def get_available_vpns(self, type : _vpn_types, **attrs):",
"get_user_rank(self, username : _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self,",
"room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) # * user",
"route=route, data=data) # $ server side issue's if r.status_code in",
"self.request(RouteList.get_game_tickets_won(username=username), **attrs) @checks.set_header_CSRF() def post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF()",
"Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) # *",
"in parameters.items()}) self.url = self.BASE + self.path except Exception as",
"get_modules_summary(self, **attrs): return self.request(RouteList.get_modules_summary(), **attrs) def get_module(self, module_code, **attrs): return",
"def get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters) # ? is",
"get_user_exist(self, username : _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs) def search_user(self,",
"return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs)",
"def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs): return self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit,",
"options[i] != None]) self.bucket = f\"{method} {path}\" class RouteList: def",
"raise errors.NotFound(request=r, route=route, data=data) # $ server side issue's if",
"__Username_regex = re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state",
"$ endpoint not found if 404 == r.status_code: raise errors.NotFound(request=r,",
"limit, \"page\": page}), **attrs) def get_user_created_rooms(self, username, limit:int=10, page:int=1, **attrs):",
"def get_network( **parameters): return Route(path=\"/api/room/network?code={network_code}\", **parameters) def get_network_cost( **parameters): return",
"None: self.static_login(session) def close(self): if self.__session: self.__session.close() def static_login(self, session):",
"self.request(RouteList.get_unseen_notifications()) self.authenticated = True self._CSRF_token = self.retrieve_CSRF_token() self.username = self.retrieve_username()",
"**parameters) def post_leave_room( **parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog,",
"Route: # TODO: add post payload capabilities BASE = \"https://www.tryhackme.com\"",
"self.url + \"&\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if",
"data=data) # $ endpoint not found if 404 == r.status_code:",
"**attrs) def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs):",
"* Leaderboards def get_leaderboards( **parameters): return Route(path=\"/api/leaderboards\", **parameters) def get_koth_leaderboards(**parameters):",
"except Exception as e: raise e class Route: # TODO:",
"**attrs): return self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs)",
"**parameters) def get_recommended_rooms( **parameters): return Route(path=\"/recommend/last-room?type=json\", **parameters) def get_questions_answered( **parameters):",
"self.request(RouteList.get_user_completed_rooms(username=username, options={\"limit\": limit, \"page\": page}), **attrs) def get_user_created_rooms(self, username, limit:int=10,",
"data=data) return data # $ no auth if r.status_code in",
"**attrs) @checks.is_authenticated() def get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) #",
"errors.NotFound(request=r, route=route, data=data) # $ server side issue's if r.status_code",
"for premium users # * VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\",",
"-room def get_user_completed_rooms_count( **parameters): return Route(path=\"/api/no-completed-rooms-public/{username}\", **parameters) def get_user_completed_rooms( **parameters):",
"self.__session.close() def static_login(self, session): self.connect_sid = session cookie = requests.cookies.create_cookie('connect.sid',",
"user profile def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user(",
"int, answer: str, **attrs): return self.request(RouteList.post_room_answer(room_code=room_code), json={\"taskNo\": taskNo, \"questionNo\": questionNo,",
"post_join_koth(self, **attrs): return self.request(RouteList.post_join_koth(), **attrs) @checks.set_header_CSRF() def post_new_koth(self, **attrs): return",
"def get_server_time( **parameters): return Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters): return",
"self.static_session = requests.Session() self.connect_sid = None self._CSRF_token = None self.username",
"Route(path=\"/api/similar-users/{username}\", **parameters) # * room def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\",",
"(https://github.com/GnarLito/thm-api-py {__version__}) Python/{sys.version_info[0]}.{sys.version_info[1]} requests/{requests.__version__}' if session is not None: self.static_login(session)",
"post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters): return Route(method=POST,",
"self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {}) def",
"return self.request(RouteList.post_terminate_machine(), json={\"code\": room_code}, **attrs) # * user -badge @checks.is_authenticated()",
"_not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def get_user_activty(self, username : _not_none,",
"**attrs) # * user def get_user_rank(self, username : _not_none, **attrs):",
"-notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters): return",
"**parameters) def get_module( **parameters): return Route(path=\"/modules/data/{module_code}\",**parameters) # * games def",
"Route(path=\"/paths/summary\", **parameters) # * modules def get_modules_summary(**parameters): return Route(path=\"/modules/summary\", **parameters)",
"VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters): return",
"self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self,",
"e: print(\"session Issue:\", e) def retrieve_CSRF_token(self): if not self.authenticated: return",
"**attrs): return self.request(RouteList.get_user_completed_rooms_count(username=username), **attrs) def get_user_completed_rooms(self, username, limit:int=10, page:int=1, **attrs):",
"**parameters) def post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters) # ?",
"**parameters): return Route(path=\"/message/group/get/{group_id}\", **parameters) # * user -room def get_user_completed_rooms_count(",
"**attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs): return self.request(RouteList.get_all_notifications(),",
"**parameters) def get_discord_user(**parameters): return Route(path=\"/api/discord/user/{username}\", **parameters) # ? rename to",
"def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards def",
"route=route, data=data) return data # $ no auth if r.status_code",
"Route(path=\"/notifications/get\", **parameters) # * user -messages def get_unseen_messages( **parameters): return",
"None try: page = self.request(RouteList.get_profile_page()) return self._HTTPClient__CSRF_token_regex.search(page).group(1) except AttributeError: self.authenticated",
"self.connect_sid = None self._CSRF_token = None self.username = None self.user_agent",
"{500, 502}: raise errors.ServerError(request=r, route=route, data=data) except Exception as e:",
"def get_room_scoreboard(self, room_code, **attrs): return self.request(RouteList.get_room_scoreboard(room_code=room_code), **attrs) def get_room_votes(self, room_code,",
"import _county_types, _leaderboard_types, _vpn_types, _not_none from . import checks from",
"* networks def get_networks( **parameters): return Route(path=\"/api/networks\", **parameters) def get_network(",
"return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters): return Route(method=POST, path=\"/api/room-percentages\", **parameters)",
"**attrs): return self.request(RouteList.get_room_tasks(room_code=room_code), **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_room_answer(self, room_code, taskNo:",
"**attrs): return self.request(RouteList.get_all_badges(), **attrs) # * user -team @checks.is_authenticated() def",
"def get_profile_page(**parameters): return Route(path=\"/profile\", **parameters) # * normal site calls",
"]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state = None self.authenticated =",
"path=\"/api/room-percentages\", **parameters) # ? is a post but it gets",
"path=\"/api/{room_code}/answer\", **parameters) def post_deploy_machine( **parameters): return Route(method=POST, path=\"/material/deploy\", **parameters) def",
"users # * VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def",
"@checks.set_header_CSRF() def post_new_koth(self, **attrs): return self.request(RouteList.post_new_koth(), **attrs) # * VPN",
"def get_user_rank(self, username : _not_none, **attrs): return self.request(RouteList.get_user_rank(username=username), **attrs) def",
"**parameters) # * user -messages def get_unseen_messages( **parameters): return Route(path=\"/message/has-unseen\",",
"**attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def get_vpn_info(self, **attrs): return",
"self.request(RouteList.get_all_badges(), **attrs) # * user -team @checks.is_authenticated() def get_team_info(self, **attrs):",
"Route(path=\"/account/subscription/cost\", **parameters) # * paths def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\",",
"username : _not_none, **attrs): return self.request(RouteList.get_discord_user(username=username), **attrs) def get_user_exist(self, username",
"in kwargs: headers['Content-Type'] = 'application/json' kwargs['data'] = utils.to_json(kwargs.pop('json')) if \"static\"",
"= re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state =",
"except Exception as e: raise errors.NotValidUrlParameters(e) else: self.url = url",
"# $ no auth if r.status_code in {401, 403}: raise",
"**kwargs): session = self.__session endpoint = route.url method = route.method",
"def get_all_group_messages(**parameters): return Route(path=\"/message/group/get-all\", **parameters) def get_group_messages( **parameters): return Route(path=\"/message/group/get/{group_id}\",",
"**parameters) # * account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) #",
"self.request(RouteList.get_networks(network_code=network_code), **attrs) # * account @checks.is_authenticated() def get_subscription_cost(self, **attrs): return",
"type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self, country: _county_types,",
"show, serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def get_series(self,",
"re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\") def __init__(self, session=None): self._state = None",
"**parameters) # * VM def get_machine_running( **parameters): return Route(path=\"/api/vm/running\", **parameters)",
"get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\",",
"Exception as e: raise e class Route: # TODO: add",
"self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(), **attrs) def",
"Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\", **parameters) # *",
"path_code, **attrs): return self.request(RouteList.get_path(path_code=path_code), **attrs) def get_public_paths(self, **attrs): return self.request(RouteList.get_public_paths(),",
"**attrs) def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def get_joined_rooms(self,",
"* room def get_new_rooms(self, **attrs): return self.request(RouteList.get_new_rooms(), **attrs) @checks.is_authenticated() def",
"self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def get_series(self, show, **attrs): return self.request(RouteList.get_series(show=show),",
"settings = kwargs.pop('settings', {}) headers = { 'User-Agent': self.user_agent }",
"# * paths def get_path( **parameters): return Route(path=\"/paths/single/{path_code}\", **parameters) def",
"def get_own_badges(self, **attrs): return self.request(RouteList.get_own_badges(), **attrs) def get_user_badges(self, username, **attrs):",
"@checks.set_header_CSRF() @checks.is_authenticated() def post_deploy_machine(self, room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\":",
"loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}), **attrs).get(room_code, {}) def get_room_tasks(self, room_code,",
"AttributeError: self.authenticated = False return None def request(self, route, **kwargs):",
"= kwargs.pop('settings', {}) headers = { 'User-Agent': self.user_agent } if",
"def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) # * paths def get_path(",
"* Leaderboards def get_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs): return self.request(RouteList.get_leaderboards(country=country.to_lower_case(),",
"= None self.authenticated = False self.__session = requests.Session() self.static_session =",
". import __version__, errors, utils from .converters import _county_types, _leaderboard_types,",
"games def get_machine_pool(self, **attrs): return self.request(RouteList.get_machine_pool(), **attrs) def get_game_detail(self, game_code,",
"self.request(RouteList.get_recommended_rooms(), **attrs) def get_questions_answered(self, **attrs): return self.request(RouteList.get_questions_answered(), **attrs) @checks.is_authenticated() def",
"= parameters.pop(\"options\", None) if parameters: try: self.path = self.path.format(**{k: _uriquote(v)",
"self.request(RouteList.get_public_paths(), **attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) # *",
"self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\":",
"type : _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs) @checks.is_authenticated() def",
"return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters) def",
"**attrs) def get_user_exist(self, username : _not_none, **attrs): return self.request(RouteList.get_user_exist(username=username), **attrs)",
"stuff def get_room_scoreboard( **parameters): return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters):",
"= self.retrieve_username() except Exception as e: print(\"session Issue:\", e) def",
"return self.request(RouteList.get_networks(),**attrs) def get_network_cost(self, network_code, **attrs): return self.request(RouteList.get_networks(network_code=network_code), **attrs) #",
"**attrs) def get_game_detail(self, game_code, **attrs): return self.request(RouteList.get_game_detail(game_code=game_code), **attrs) def get_recent_games(self,",
"def get_user_exist( **parameters): return Route(path=\"/api/user/exist/{username}\", **parameters) def search_user( **parameters): return",
"= route.url method = route.method settings = kwargs.pop('settings', {}) headers",
"get_recent_games(self, **attrs): return self.request(RouteList.get_recent_games(), **attrs) def get_user_games(self, **attrs): return self.request(RouteList.get_user_games(),",
"def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters): return Route(path=\"/vpn/my-data\",",
"= None self._CSRF_token = None self.username = None self.user_agent =",
"self.BASE + self.path options = parameters.pop(\"options\", None) if parameters: try:",
"def get_user_created_rooms( **parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) # * user def",
"room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(), json={\"code\":",
"method=GET, path='', **parameters): self.method = method self._path = path self.path",
"def get_available_vpns(self, type : _vpn_types, **attrs): return self.request(RouteList.get_available_vpns(options={\"type\": type}), **attrs)",
"return self.request(RouteList.get_leaderboards(country=country.to_lower_case(), type=type), **attrs) def get_koth_leaderboards(self, country: _county_types, type:_leaderboard_types, **attrs):",
"get_joined_rooms(self, **attrs): return self.request(RouteList.get_joined_rooms(), **attrs) @checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs):",
"**attrs): return self.request(RouteList.get_user_activty(username=username), **attrs) @checks.is_authenticated() def get_all_friends(self, **attrs): return self.request(RouteList.get_all_friends(),",
"**parameters) def get_network_cost( **parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account",
"self.url + \"?\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if",
"_not_none, **attrs): return self.request(RouteList.search_user(username=username), **attrs) # * room def get_new_rooms(self,",
"return self.request(RouteList.get_glossary_terms(), **attrs) # * Leaderboards def get_leaderboards(self, country: _county_types,",
"module_code, **attrs): return self.request(RouteList.get_module(module_code), **attrs) # * games def get_machine_pool(self,",
"post_room_answer(self, room_code, taskNo: int, questionNo: int, answer: str, **attrs): return",
"re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const username[ ]{0,1}=[ ]{0,1}[\\\"|'](.{1,16})[\\\"|']\")",
"VM def get_machine_running(self, **attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self,",
"for k, v in parameters.items()}) self.url = self.BASE + self.path",
"Route(path=\"/message/group/get/{group_id}\", **parameters) # * user -room def get_user_completed_rooms_count( **parameters): return",
"return Route(path=\"/api/badges/mine\", **parameters) def get_user_badges(**parameters): return Route(path=\"/api/badges/get/{username}\", **parameters) def get_all_badges(",
"\"&\" + \"&\".join([f\"{i}={options[i]}\" for i in options.keys() if options[i] !=",
"get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\", **parameters)",
"type:_leaderboard_types, **attrs): return self.request(RouteList.get_koth_leaderboards(country=country.to_lower_case(), type=type), **attrs) # * networks def",
"**parameters): return Route(method=POST, path=\"/api/room/leave\", **parameters) class HTTP(request_cog, HTTPClient): # *",
"room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated() def post_leave_room(self, room_code, **attrs): return self.request(RouteList.post_leave_room(),",
"return Route(method=POST, path=\"/api/vm/terminate\", **parameters) # * user -badge def get_own_badges(",
"get_group_messages(self, group_id, **attrs): return self.request(RouteList.get_group_messages(group_id), **attrs) # * user -room",
"room_code}, **attrs) # * user -badge @checks.is_authenticated() def get_own_badges(self, **attrs):",
"return self.request(RouteList.get_series(show=show), **attrs) def get_glossary_terms(self, **attrs): return self.request(RouteList.get_glossary_terms(), **attrs) #",
"post_terminate_machine( **parameters): return Route(method=POST, path=\"/api/vm/terminate\", **parameters) # * user -badge",
"return Route(path=\"/api/room/scoreboard?code={room_code}\", **parameters) def get_room_votes( **parameters): return Route(path=\"/api/room/votes?code={room_code}\", **parameters) def",
"**parameters) def post_join_koth( **parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth(",
"kwargs[\"data\"][\"_CSRF\"] = self._CSRF_token # TODO: retries, Pagenator try: with session.request(method,",
"from . import checks from .cog import request_cog GET='get' POST='post'",
"json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() def post_terminate_machine(self, room_code, **attrs): return self.request(RouteList.post_terminate_machine(),",
"**parameters): return Route(path=\"/api/room/cost?code={network_code}\", **parameters) # * account def get_subscription_cost(**parameters): return",
"**attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated()",
"* VPN def get_available_vpns(**parameters): return Route(path=\"/vpn/get-available-vpns\", **parameters) def get_vpn_info( **parameters):",
"r.status_code in {500, 502}: raise errors.ServerError(request=r, route=route, data=data) except Exception",
"self._CSRF_token = self.retrieve_CSRF_token() self.username = self.retrieve_username() except Exception as e:",
"room def get_new_rooms( **parameters): return Route(path=\"/api/new-rooms\", **parameters) def get_recommended_rooms( **parameters):",
"**attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs) @checks.is_authenticated() def get_room_scoreboard(self, room_code,",
"== r.status_code: raise errors.NotFound(request=r, route=route, data=data) # $ server side",
"**parameters) # ? list posibility def get_room_tasks( **parameters): return Route(path=\"/api/tasks/{room_code}\",",
"404 == r.status_code: raise errors.NotFound(request=r, route=route, data=data) # $ server",
"user -notifications def get_unseen_notifications(**parameters): return Route(path=\"/notifications/has-unseen\", **parameters) def get_all_notifications( **parameters):",
"return Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters) def",
"True self._CSRF_token = self.retrieve_CSRF_token() self.username = self.retrieve_username() except Exception as",
"self.authenticated = False return None def request(self, route, **kwargs): session",
"False self.__session = requests.Session() self.static_session = requests.Session() self.connect_sid = None",
"get_unseen_notifications(self, **attrs): return self.request(RouteList.get_unseen_notifications(), **attrs) @checks.is_authenticated() def get_all_notifications(self, **attrs): return",
"def get_user_games( **parameters): return Route(path=\"/games/koth/user/games\", **parameters) def get_game_tickets_won(**parameters): return Route(path=\"/games/tickets/won?username={username}\",",
"# TODO: retries, Pagenator try: with session.request(method, endpoint, **kwargs) as",
"get_practise_rooms(self, **attrs): return self.request(RouteList.get_practise_rooms(), **attrs) def get_serie(self, show, serie_code, **attrs):",
"str) else v for k, v in parameters.items()}) self.url =",
"def post_reset_room_progress(**parameters): return Route(method=POST, path=\"/api/reset-progress\", **parameters) def post_leave_room( **parameters): return",
"session = self.__session endpoint = route.url method = route.method settings",
"* account def get_subscription_cost(**parameters): return Route(path=\"/account/subscription/cost\", **parameters) # * paths",
"**attrs): return self.request(RouteList.get_user_games(), **attrs) def get_game_tickets_won(self, username, **attrs): return self.request(RouteList.get_game_tickets_won(username=username),",
"room_code, uploadId, **attrs): return self.request(RouteList.post_deploy_machine(), json={\"roomCode\": room_code, \"id\": uploadId}, **attrs)",
"bool=True, **attrs): return self.request(RouteList.get_room_details(room_code=room_code, options={\"loadWriteUps\": loadWriteUps, \"loadCreators\": loadCreators, \"loadUser\": loadUser}),",
"@checks.is_authenticated() def get_room_percentages(self, room_codes, **attrs): return self.request(RouteList.get_room_percetages(), json={\"rooms\": room_codes}, **attrs)",
"return Route(path=\"/glossary/all-terms\", **parameters) # * Leaderboards def get_leaderboards( **parameters): return",
"def get_recent_games( **parameters): return Route(path=\"/games/koth/recent/games\", **parameters) def get_user_games( **parameters): return",
"post_reset_room_progress(self, room_code, **attrs): return self.request(RouteList.post_reset_room_progress(), json={\"code\": room_code}, **attrs) @checks.set_header_CSRF() @checks.is_authenticated()",
"**parameters): return Route(path=\"/api/created-rooms/{username}\", **parameters) # * user def get_user_rank( **parameters):",
"except Exception as e: print(\"session Issue:\", e) def retrieve_CSRF_token(self): if",
"**parameters) class HTTP(request_cog, HTTPClient): # * normal site calls def",
"Route(path=\"/api/site-stats\", **parameters) def get_practise_rooms( **parameters): return Route(path=\"/api/practice-rooms\", **parameters) def get_series(",
"get_serie(self, show, serie_code, **attrs): return self.request(RouteList.get_series(show=show, options={\"name\": serie_code}), **attrs) def",
"if \"static\" in settings: session = self.static_session if \"CSRF\" in",
"**parameters) def get_all_badges( **parameters): return Route(path=\"/api/badges/get\", **parameters) # * user",
"None self._CSRF_token = None self.username = None self.user_agent = f'Tryhackme:",
"return self.request(RouteList.get_subscription_cost(), **attrs) # * paths def get_path(self, path_code, **attrs):",
"user -messages @checks.is_authenticated() def get_unseen_messages(self, **attrs): return self.request(RouteList.get_unseen_messages(), **attrs) @checks.is_authenticated()",
"return Route(path=\"/api/server-time\", **parameters) def get_site_stats( **parameters): return Route(path=\"/api/site-stats\", **parameters) def",
"def get_joined_rooms( **parameters): return Route(path=\"/api/my-rooms\", **parameters) def get_room_percetages( **parameters): return",
"**parameters): return Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters): return Route(method=POST,",
"HTTPClient: __CSRF_token_regex = re.compile(\"const csrfToken[ ]{0,1}=[ ]{0,1}[\\\"|'](.{36})[\\\"|']\") __Username_regex = re.compile(\"const",
"**attrs) def get_path_summary(self, **attrs): return self.request(RouteList.get_path_summary(), **attrs) # * modules",
"**attrs): return self.request(RouteList.get_machine_running(), **attrs) @checks.set_header_CSRF() def post_renew_machine(self, room_code, **attrs): return",
"Route(method=POST, path=\"/games/koth/new\", **parameters) def post_new_koth( **parameters): return Route(method=POST, path=\"/games/koth/join-public\", **parameters)"
] |
[
"import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv",
"1 webui_host = '127.0.0.1' for exp in experiments.values(): if run_args.eager:",
"Remove any wandb related configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def",
"and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\":",
"run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, } } if arg_parser is",
"eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add evaluation config to the current",
"not exp.get(\"run\"): arg_parser.error(\"the following arguments are required: --run\") if not",
"run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial",
"None: for exp in experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the following",
"import _make_scheduler from ray.tune.utils import merge_dicts from flatlander.envs import get_eval_config",
"= None): if run_args.config_file: with open(run_args.config_file) as f: experiments =",
"verbose = 1 webui_host = '127.0.0.1' for exp in experiments.values():",
"experiments=experiments) if args.eval: self.evaluate(exp) if args.config_file: # TODO should be",
"= True if run_args.bind_all: webui_host = \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks']",
"wandb related configs if eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb'] #",
"= 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\"))",
"\"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env),",
"ArgumentParser from pathlib import Path import gym import ray import",
"None else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is not None else",
"[WandbLogger, TBXLogger] if args.ray_num_nodes: cluster = Cluster() for _ in",
"if args.ray_num_gpus is not None else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args),",
"import Tuple from ray.cluster_utils import Cluster from ray.rllib.utils import try_import_tf,",
"register_env from ray.tune.logger import TBXLogger from ray.tune.resources import resources_to_json from",
"} obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space",
"rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if",
"\"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in",
"make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1,",
"if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose = 3 if run_args.trace:",
"in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory,",
"or 1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else:",
"from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics",
"= { 'on_episode_end': on_episode_end, } return experiments, verbose @staticmethod def",
"dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, } }",
"= yaml.safe_load(f) else: experiments = { run_args.experiment_name: { # i.e.",
"Path import gym import ray import ray.tune.result as ray_results import",
"== \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del",
"required: --envs\") return experiments @staticmethod def setup_grouping(config: dict): grouping =",
"{}) }, \"policy_mapping_fn\": lambda agent_id: \"meta\" if 'meta' in str(agent_id)",
"2 if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose = 3 if",
"evaluation config to the current config exp['config'] = merge_dicts(exp['config'], eval_configs)",
"is not None: for exp in experiments.values(): if not exp.get(\"run\"):",
"'meta' in str(agent_id) else \"agent\" } def apply_args(self, run_args, experiments:",
"if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is not None:",
"True if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is not",
"if eval_seed and eval_env_config: # We override the envs seed",
"# Remove any wandb related configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb']",
"the current config exp['config'] = merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config']",
"Cluster from ray.rllib.utils import try_import_tf, try_import_torch from ray.tune import run_experiments,",
"if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose = 2 if run_args.vv:",
"exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] = [WandbLogger, TBXLogger] if args.ray_num_nodes: cluster",
"run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end': on_episode_end, } return experiments, verbose",
"\"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\":",
"from the evaluation config eval_env_config['seed'] = eval_seed # Remove any",
"any wandb related configs if eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb']",
"--eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all: webui_host",
"def setup_policy_map(self, config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] =",
"redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing n_cpu = multiprocessing.cpu_count() import tensorflow",
"experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if",
"= Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config:",
"= make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"meta\": (None, obs_space.spaces[0],",
"config[\"multiagent\"] = { \"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)),",
"= merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config =",
"FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import WandbLogger from",
"= { run_args.experiment_name: { # i.e. log to ~/ray_results/default \"run\":",
"run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)),",
"if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager to enable tracing.\")",
"range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def",
"args.ray_num_gpus) ray.init( local_mode=True if args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus",
"str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])},",
"not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"]",
"try_import_tf() self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args,",
"ValueError(\"Must enable --eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True if",
"not exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments are",
"config: dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = {",
"tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE:",
"{\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1],",
"env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, } } if",
"cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory)",
"os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms = [\"QMIX\",",
"run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\":",
"args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init( local_mode=True if args.local else",
"GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from",
"memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing n_cpu = multiprocessing.cpu_count() import",
"eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove any wandb related",
"= Cluster() for _ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1,",
"~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\":",
"= get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') #",
"flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import",
"be in exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] = [WandbLogger,",
"self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser:",
"Cluster() for _ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus",
"from ray.tune.utils import merge_dicts from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse",
"if arg_parser is not None: for exp in experiments.values(): if",
"== \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is not None: experiments, verbose",
"f: experiments = yaml.safe_load(f) else: experiments = { run_args.experiment_name: {",
"import os from argparse import ArgumentParser from pathlib import Path",
"@staticmethod def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed =",
"\"DEBUG\" verbose = 3 if run_args.trace: if not exp[\"config\"].get(\"eager\"): raise",
"load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser: ArgumentParser = None): if",
"FlatlandSparse from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from",
"ArgumentParser = None): if run_args.config_file: with open(run_args.config_file) as f: experiments",
"args=None): verbose = 1 webui_host = \"localhost\" for exp in",
"ray.init(address=cluster.address) else: import multiprocessing n_cpu = multiprocessing.cpu_count() import tensorflow as",
"import FlatlandSparse from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv",
"in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\" + str(agent_id)} def setup_hierarchical_policies(self,",
"gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) },",
"True if run_args.bind_all: webui_host = \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] =",
"verbose = 3 if run_args.trace: if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must",
"len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS",
"exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict, args=None): verbose = 1 webui_host",
"\", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init( local_mode=True if args.local",
"load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class",
"Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for",
"def setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"]",
"apply_args(self, run_args, experiments: dict): verbose = 1 webui_host = '127.0.0.1'",
"config exp['config'] = merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config')",
"experiments @staticmethod def setup_grouping(config: dict): grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])),",
"exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config: # We override the envs",
"from ray.rllib.utils import try_import_tf, try_import_torch from ray.tune import run_experiments, register_env",
"import multiprocessing n_cpu = multiprocessing.cpu_count() import tensorflow as tf n_gpu",
"\"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": (",
"_make_scheduler from ray.tune.utils import merge_dicts from flatlander.envs import get_eval_config from",
"to the current config exp['config'] = merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'):",
"args is not None: experiments, verbose = self.apply_args(run_args=args, experiments=experiments) if",
"run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop,",
"run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir,",
"from pathlib import Path import gym import ray import ray.tune.result",
"config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"pol_\" + str(i): (None, obs_space,",
"config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0,",
"run_args.experiment_name: { # i.e. log to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\":",
"webui_host = '127.0.0.1' for exp in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"]",
"os from argparse import ArgumentParser from pathlib import Path import",
"current config exp['config'] = merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] =",
"low=0, shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\":",
"args.eval: self.evaluate(exp) if args.config_file: # TODO should be in exp['config']",
"= try_import_tf() self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def",
"related configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict,",
"= 2 if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose = 3",
"experiments: dict): verbose = 1 webui_host = '127.0.0.1' for exp",
"+ str(agent_id)} def setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"],",
"ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler from ray.tune.utils import",
"exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config:",
"override the envs seed from the evaluation config eval_env_config['seed'] =",
"1 webui_host = \"localhost\" for exp in experiments.values(): if exp.get(\"config\",",
"= args.config_file exp['loggers'] = [WandbLogger, TBXLogger] if args.ray_num_nodes: cluster =",
"(None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda agent_id: \"meta\" if",
"False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is not None else",
"args.ray_num_gpus is not None else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args), queue_trials=args.queue_trials,",
"ray.tune.utils import merge_dicts from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import",
"(None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space,",
"in str(agent_id) else \"agent\" } def apply_args(self, run_args, experiments: dict):",
"rllib_dir = Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if",
"exp[\"config\"][\"log_level\"] = \"INFO\" verbose = 2 if run_args.vv: exp[\"config\"][\"log_level\"] =",
"import resources_to_json from ray.tune.tune import _make_scheduler from ray.tune.utils import merge_dicts",
"make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"pol_\" + str(i): (None,",
"yaml from gym.spaces import Tuple from ray.cluster_utils import Cluster from",
"run_args.num_samples, \"upload_dir\": run_args.upload_dir, } } if arg_parser is not None:",
"'on_episode_end': on_episode_end, } return experiments, verbose @staticmethod def evaluate(exp): eval_configs",
"experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the following arguments are required: --run\")",
"{}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file =",
"from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env",
"ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms",
"import ArgumentParser from pathlib import Path import gym import ray",
"@staticmethod def get_experiments(run_args, arg_parser: ArgumentParser = None): if run_args.config_file: with",
"n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is not None else n_gpu) run_experiments(",
"_ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or 1,",
"and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments are required: --envs\")",
"arg_parser.error(\"the following arguments are required: --run\") if not exp.get(\"envs\") and",
"num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing",
"grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space()",
"<reponame>wullli/flatlander<gh_stars>1-10 import os from argparse import ArgumentParser from pathlib import",
"run(self, experiments: dict, args=None): verbose = 1 webui_host = \"localhost\"",
"return experiments, verbose @staticmethod def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator',",
"run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config,",
"raise ValueError(\"Must enable --eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True",
"exp.get(\"run\"): arg_parser.error(\"the following arguments are required: --run\") if not exp.get(\"envs\")",
"ray.cluster_utils import Cluster from ray.rllib.utils import try_import_tf, try_import_torch from ray.tune",
"with open(run_args.config_file) as f: experiments = yaml.safe_load(f) else: experiments =",
"= \"DEBUG\" verbose = 3 if run_args.trace: if not exp[\"config\"].get(\"eager\"):",
"exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"]",
"eval_seed and eval_env_config: # We override the envs seed from",
"= True if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is",
"AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS: \",",
"envs seed from the evaluation config eval_env_config['seed'] = eval_seed #",
"False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] ==",
"to enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all: webui_host =",
"ARGS: \", args.ray_num_gpus) ray.init( local_mode=True if args.local else False, address=args.ray_address,",
"ray.tune import run_experiments, register_env from ray.tune.logger import TBXLogger from ray.tune.resources",
"\"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, }",
"= \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end': on_episode_end, }",
"eval_env_config['seed'] = eval_seed # Remove any wandb related configs if",
"print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init( local_mode=True if args.local else False,",
"None else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args), queue_trials=args.queue_trials, resume=args.resume, verbose=verbose, concurrent=True)",
"required: --run\") if not exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the",
"from gym.spaces import Tuple from ray.cluster_utils import Cluster from ray.rllib.utils",
"\", n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus)",
"experiments, verbose @staticmethod def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\"))",
"False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100",
"exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict, args=None): verbose =",
"tracing.\") exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all: webui_host = \"0.0.0.0\" if",
"exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"]",
"following arguments are required: --envs\") return experiments @staticmethod def setup_grouping(config:",
"from ray.tune.logger import TBXLogger from ray.tune.resources import resources_to_json from ray.tune.tune",
"if not exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments",
"flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import",
"None): if run_args.config_file: with open(run_args.config_file) as f: experiments = yaml.safe_load(f)",
"from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR",
"obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space()",
"import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end",
"{}).get(\"envs\"): arg_parser.error(\"the following arguments are required: --envs\") return experiments @staticmethod",
"merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config')",
"arg_parser is not None: for exp in experiments.values(): if not",
"= try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser: ArgumentParser =",
"_ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser: ArgumentParser",
"enable --eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all:",
"= 1 webui_host = '127.0.0.1' for exp in experiments.values(): if",
"dict): grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"],",
"# i.e. log to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\":",
"\"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end': on_episode_end, } return",
"self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if",
"resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples,",
"evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config',",
"should be in exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] =",
"n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS",
"range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\" + str(agent_id)} def setup_hierarchical_policies(self, config:",
"from ray.tune.tune import _make_scheduler from ray.tune.utils import merge_dicts from flatlander.envs",
"verbose = self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp) if args.config_file: #",
"\"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add evaluation config",
"from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader",
"flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import",
"exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager to enable tracing.\") exp[\"config\"][\"eager_tracing\"] =",
"3 if run_args.trace: if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager",
"1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import",
"tensorflow as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu)",
"group_algorithms = [\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf = try_import_tf() self.torch,",
"import TBXLogger from ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler",
"\"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\": (None,",
"import run_experiments, register_env from ray.tune.logger import TBXLogger from ray.tune.resources import",
"return experiments @staticmethod def setup_grouping(config: dict): grouping = { \"group_1\":",
"resources_to_json from ray.tune.tune import _make_scheduler from ray.tune.utils import merge_dicts from",
"webui_host = \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end': on_episode_end,",
"if args.ray_num_nodes: cluster = Cluster() for _ in range(args.ray_num_nodes): cluster.add_node(",
"ray.init( local_mode=True if args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if",
"configs if eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove any",
"run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose = 2 if run_args.vv: exp[\"config\"][\"log_level\"]",
"if args.config_file: # TODO should be in exp['config'] directly exp['config']['env_config']['yaml_config']",
"= len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu)",
"exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False):",
"_ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])])",
"import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\")",
"agent_id: \"meta\" if 'meta' in str(agent_id) else \"agent\" } def",
"exp['config']['callbacks'] = { 'on_episode_end': on_episode_end, } return experiments, verbose @staticmethod",
"import gym import ray import ray.tune.result as ray_results import yaml",
"str(agent_id) else \"agent\" } def apply_args(self, run_args, experiments: dict): verbose",
"enable tracing.\") exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all: webui_host = \"0.0.0.0\"",
"{ \"policies\": {\"pol_\" + str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i})",
"and eval_env_config: # We override the envs seed from the",
"ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf = try_import_tf()",
"if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict, args=None): verbose",
"is not None: experiments, verbose = self.apply_args(run_args=args, experiments=experiments) if args.eval:",
"get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import make_obs from",
"exp in experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the following arguments are",
"not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] =",
"are required: --envs\") return experiments @staticmethod def setup_grouping(config: dict): grouping",
"import tensorflow as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \",",
"if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"]",
"= rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\"))",
"exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]):",
"configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict, args=None):",
"\"QMIXApex\"] def __init__(self): self.tf = try_import_tf() self.torch, _ = try_import_torch()",
"shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda",
"\"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and",
"flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\", \"..\",",
"run_args.upload_dir, } } if arg_parser is not None: for exp",
"\"upload_dir\": run_args.upload_dir, } } if arg_parser is not None: for",
"self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp) if args.config_file: # TODO should",
"str(input_file) if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\"",
"the evaluation config eval_env_config['seed'] = eval_seed # Remove any wandb",
"import ray import ray.tune.result as ray_results import yaml from gym.spaces",
"True if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if run_args.v: exp[\"config\"][\"log_level\"] =",
"not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments are required: --envs\") return",
"config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for _",
"run_args.config_file: with open(run_args.config_file) as f: experiments = yaml.safe_load(f) else: experiments",
"= { \"policies\": {\"pol_\" + str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\":",
"def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config',",
"for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\" + str(agent_id)}",
"exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed and",
"def __init__(self): self.tf = try_import_tf() self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__))",
"exp['config'] = merge_dicts(exp['config'], eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config",
"We override the envs seed from the evaluation config eval_env_config['seed']",
"import on_episode_end from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import load_envs,",
"if 'meta' in str(agent_id) else \"agent\" } def apply_args(self, run_args,",
"str(agent_id)} def setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space()",
"if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\" or",
"from ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler from ray.tune.utils",
"webui_host = \"localhost\" for exp in experiments.values(): if exp.get(\"config\", {}).get(\"input\"):",
"print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS:",
"import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations import make_obs",
"range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory,",
"address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is not None else n_cpu,",
"else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args), queue_trials=args.queue_trials, resume=args.resume, verbose=verbose, concurrent=True) ray.shutdown()",
"\"pol_\" + str(agent_id)} def setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple =",
"\"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda agent_id: \"meta\"",
"eval_env_config: # We override the envs seed from the evaluation",
"lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config: dict):",
"get_experiments(run_args, arg_parser: ArgumentParser = None): if run_args.config_file: with open(run_args.config_file) as",
"if args is not None: experiments, verbose = self.apply_args(run_args=args, experiments=experiments)",
"= os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms =",
"run_experiments, register_env from ray.tune.logger import TBXLogger from ray.tune.resources import resources_to_json",
"\"meta\" if 'meta' in str(agent_id) else \"agent\" } def apply_args(self,",
"multiprocessing.cpu_count() import tensorflow as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE:",
"{}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add evaluation",
"self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\":",
"is not None else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args), queue_trials=args.queue_trials, resume=args.resume,",
"exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose = 3 if run_args.trace: if not",
"FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config: dict): obs_space =",
"if exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not",
"else: experiments = { run_args.experiment_name: { # i.e. log to",
"as f: experiments = yaml.safe_load(f) else: experiments = { run_args.experiment_name:",
"TBXLogger] if args.ray_num_nodes: cluster = Cluster() for _ in range(args.ray_num_nodes):",
"log to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\":",
"run_args, experiments: dict): verbose = 1 webui_host = '127.0.0.1' for",
"# add evaluation config to the current config exp['config'] =",
"ray.tune.tune import _make_scheduler from ray.tune.utils import merge_dicts from flatlander.envs import",
"print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS:",
"gym import ray import ray.tune.result as ray_results import yaml from",
"arg_parser.error(\"the following arguments are required: --envs\") return experiments @staticmethod def",
"1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing n_cpu =",
"any wandb related configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self,",
"as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS",
"run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore,",
"def run(self, experiments: dict, args=None): verbose = 1 webui_host =",
"not None else n_gpu) run_experiments( experiments, scheduler=_make_scheduler(args), queue_trials=args.queue_trials, resume=args.resume, verbose=verbose,",
"verbose @staticmethod def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed",
"eval_env_config['wandb'] # Remove any wandb related configs if exp['config']['evaluation_config'].get('wandb'): del",
"if run_args.trace: if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager to",
"obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {})",
"on_episode_end, } return experiments, verbose @staticmethod def evaluate(exp): eval_configs =",
"for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping,",
"from ray.tune import run_experiments, register_env from ray.tune.logger import TBXLogger from",
"multiprocessing n_cpu = multiprocessing.cpu_count() import tensorflow as tf n_gpu =",
"if run_args.config_file: with open(run_args.config_file) as f: experiments = yaml.safe_load(f) else:",
"else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is not None else n_gpu)",
"= eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add evaluation config to the",
"experiments: dict, args=None): verbose = 1 webui_host = \"localhost\" for",
"import try_import_tf, try_import_torch from ray.tune import run_experiments, register_env from ray.tune.logger",
"exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is not None: experiments,",
"class ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf =",
"exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] = [WandbLogger, TBXLogger] if",
"dict): verbose = 1 webui_host = '127.0.0.1' for exp in",
"flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import",
"not None: experiments, verbose = self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp)",
"seed from the evaluation config eval_env_config['seed'] = eval_seed # Remove",
"= Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"]",
"exp in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] = True if run_args.torch:",
"i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\" + str(agent_id)} def",
"if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True",
"import merge_dicts from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse",
"\"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"] def __init__(self):",
"directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] = [WandbLogger, TBXLogger] if args.ray_num_nodes:",
"register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self,",
"FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda agent_id: \"meta\" if 'meta' in",
"isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file",
"== \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"]",
"--envs\") return experiments @staticmethod def setup_grouping(config: dict): grouping = {",
"self.tf = try_import_tf() self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod",
"wandb related configs if exp['config']['evaluation_config'].get('wandb'): del exp['config']['evaluation_config']['wandb'] def run(self, experiments:",
"exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] =",
"from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger",
"exp[\"config\"][\"eager_tracing\"] = True if run_args.bind_all: webui_host = \"0.0.0.0\" if run_args.log_flatland_stats:",
"lambda agent_id: \"pol_\" + str(agent_id)} def setup_hierarchical_policies(self, config: dict): obs_space:",
"{ \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _",
"\"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"] def",
"args.ray_num_nodes: cluster = Cluster() for _ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus",
"grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"],",
"if args.eval: self.evaluate(exp) if args.config_file: # TODO should be in",
"for exp in experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\",",
"dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"])",
"ray_results import yaml from gym.spaces import Tuple from ray.cluster_utils import",
"\"local_dir\": run_args.local_dir, \"resources_per_trial\": ( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\":",
"import WandbLogger from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(),",
"\"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args is not None: experiments, verbose =",
"True if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose = 2 if",
"self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\"))",
"exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] =",
"obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda",
"{}).get('seed') # add evaluation config to the current config exp['config']",
"experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] = True if run_args.torch: exp[\"config\"][\"use_pytorch\"] =",
"num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address)",
"flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import",
"exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"] == \"flatland_sparse_hierarchical\":",
"arg_parser: ArgumentParser = None): if run_args.config_file: with open(run_args.config_file) as f:",
"\"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, } } if arg_parser",
"'127.0.0.1' for exp in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] = True",
"yaml.safe_load(f) else: experiments = { run_args.experiment_name: { # i.e. log",
"if not exp.get(\"run\"): arg_parser.error(\"the following arguments are required: --run\") if",
"= Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space",
"} if arg_parser is not None: for exp in experiments.values():",
"= exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config: #",
"= self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp) if args.config_file: # TODO",
"import Path import gym import ray import ray.tune.result as ray_results",
"= \"localhost\" for exp in experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if",
"list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])])",
"input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"] in self.group_algorithms:",
"ray.tune.result as ray_results import yaml from gym.spaces import Tuple from",
"} } if arg_parser is not None: for exp in",
"{ \"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}), \"agent\":",
"exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments are required: --envs\") return experiments",
"is not None else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is not",
"ray.tune.logger import TBXLogger from ray.tune.resources import resources_to_json from ray.tune.tune import",
"\"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf",
"if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed",
"import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import on_episode_end from flatlander.logging.wandb_logger import WandbLogger",
"for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for _ in",
"in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space))",
"from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from flatlander.envs.observations",
"obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"meta\":",
"args.ray_num_cpus is not None else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is",
"[\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf = try_import_tf() self.torch, _ =",
"\"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"]",
"\"agent\" } def apply_args(self, run_args, experiments: dict): verbose = 1",
"from argparse import ArgumentParser from pathlib import Path import gym",
"load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser: ArgumentParser = None): if run_args.config_file:",
"config[\"multiagent\"] = { \"policies\": {\"pol_\" + str(i): (None, obs_space, FillingFlatlandGymEnv.action_space,",
"else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is not None",
"object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing n_cpu = multiprocessing.cpu_count()",
"= True if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose = 2",
"config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config: dict): obs_space",
"ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init( local_mode=True if",
"run_args.eager: exp[\"config\"][\"eager\"] = True if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if",
"{ 'on_episode_end': on_episode_end, } return experiments, verbose @staticmethod def evaluate(exp):",
"i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\" +",
"n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS AVAILABLE: \", n_cpu) print(\"NUM_GPUS AVAILABLE: \",",
"= '127.0.0.1' for exp in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] =",
"not None: for exp in experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the",
"exp['loggers'] = [WandbLogger, TBXLogger] if args.ray_num_nodes: cluster = Cluster() for",
"try_import_tf, try_import_torch from ray.tune import run_experiments, register_env from ray.tune.logger import",
"{}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir",
"\"policy_mapping_fn\": lambda agent_id: \"pol_\" + str(agent_id)} def setup_hierarchical_policies(self, config: dict):",
"i.e. log to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num,",
"= { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for",
"@staticmethod def setup_grouping(config: dict): grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), }",
"act_space=act_space)) def setup_policy_map(self, config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"]",
"if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir =",
"args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is not",
"in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False):",
"_ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space,",
"= 3 if run_args.trace: if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable",
"exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if",
"print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init( local_mode=True",
"= exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config: # We override the",
"exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if args",
"\"localhost\" for exp in experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if not",
"act_space = Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda",
"import Cluster from ray.rllib.utils import try_import_tf, try_import_torch from ray.tune import",
"exp in experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"),",
"+ str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i in",
"if exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\",",
"verbose = 1 webui_host = \"localhost\" for exp in experiments.values():",
"}, \"policy_mapping_fn\": lambda agent_id: \"meta\" if 'meta' in str(agent_id) else",
"= 1 webui_host = \"localhost\" for exp in experiments.values(): if",
"setup_grouping(config: dict): grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space =",
"dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"pol_\"",
"eval_seed # Remove any wandb related configs if eval_env_config: if",
"for exp in experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the following arguments",
"setup_policy_map(self, config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = {",
"{\"agent_id\": i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id: \"pol_\"",
"self.evaluate(exp) if args.config_file: # TODO should be in exp['config'] directly",
"cluster = Cluster() for _ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or",
"if args.ray_num_cpus is not None else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus",
"eval_configs) if exp['config'].get('evaluation_config'): exp['config']['evaluation_config']['env_config'] = exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if",
"= { \"policies\": {\"meta\": (None, obs_space.spaces[0], gym.spaces.Box(high=1, low=0, shape=(1,)), {}),",
"Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file) if exp[\"run\"] in",
"eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add evaluation config to",
"flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR =",
"args.config_file exp['loggers'] = [WandbLogger, TBXLogger] if args.ray_num_nodes: cluster = Cluster()",
"arguments are required: --envs\") return experiments @staticmethod def setup_grouping(config: dict):",
"\"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\": run_args.restore, \"num_samples\": run_args.num_samples, \"upload_dir\":",
"config to the current config exp['config'] = merge_dicts(exp['config'], eval_configs) if",
"del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"]",
"gym.spaces import Tuple from ray.cluster_utils import Cluster from ray.rllib.utils import",
"eval_configs = get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed')",
"load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner:",
"in exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers'] = [WandbLogger, TBXLogger]",
"= \"INFO\" verbose = 2 if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\"",
"# We override the envs seed from the evaluation config",
"del exp['config']['evaluation_config']['wandb'] def run(self, experiments: dict, args=None): verbose = 1",
"pathlib import Path import gym import ray import ray.tune.result as",
"experiments = { run_args.experiment_name: { # i.e. log to ~/ray_results/default",
"Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups(",
"self.setup_hierarchical_policies(exp.get(\"config\")) if args is not None: experiments, verbose = self.apply_args(run_args=args,",
"to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr,",
"import yaml from gym.spaces import Tuple from ray.cluster_utils import Cluster",
"lambda agent_id: \"meta\" if 'meta' in str(agent_id) else \"agent\" }",
"merge_dicts from flatlander.envs import get_eval_config from flatlander.envs.flatland_sparse import FlatlandSparse from",
"try_import_torch from ray.tune import run_experiments, register_env from ray.tune.logger import TBXLogger",
"if run_args.eager: exp[\"config\"][\"eager\"] = True if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True",
"config eval_env_config['seed'] = eval_seed # Remove any wandb related configs",
"\"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"] = 100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"] ==",
"def get_experiments(run_args, arg_parser: ArgumentParser = None): if run_args.config_file: with open(run_args.config_file)",
"(None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\":",
"args.config_file: # TODO should be in exp['config'] directly exp['config']['env_config']['yaml_config'] =",
"ray.rllib.utils import try_import_tf, try_import_torch from ray.tune import run_experiments, register_env from",
"run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose = 3 if run_args.trace: if",
"--run\") if not exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following",
"following arguments are required: --run\") if not exp.get(\"envs\") and not",
"{\"pol_\" + str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i",
"} def apply_args(self, run_args, experiments: dict): verbose = 1 webui_host",
"dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\":",
"\"policies\": {\"pol_\" + str(i): (None, obs_space, FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for",
"try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__)) @staticmethod def get_experiments(run_args, arg_parser: ArgumentParser = None):",
"n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus) ray.init(",
"in experiments.values(): if exp.get(\"config\", {}).get(\"input\"): if not isinstance(exp.get(\"config\", {}).get(\"input\"), dict):",
"experiments = yaml.safe_load(f) else: experiments = { run_args.experiment_name: { #",
"the envs seed from the evaluation config eval_env_config['seed'] = eval_seed",
"if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if exp[\"run\"] == \"contrib/MADDPG\": exp.get(\"config\")[\"env_config\"][\"learning_starts\"]",
"num_cpus=args.ray_num_cpus if args.ray_num_cpus is not None else n_cpu, num_gpus=args.ray_num_gpus if",
"run_args.bind_all: webui_host = \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end':",
"import ray.tune.result as ray_results import yaml from gym.spaces import Tuple",
"Remove any wandb related configs if eval_env_config: if eval_env_config.get('wandb'): del",
"{ # i.e. log to ~/ray_results/default \"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq,",
"} return experiments, verbose @staticmethod def evaluate(exp): eval_configs = get_eval_config(exp['config'].get('env_config',",
"for _ in range(args.ray_num_nodes): cluster.add_node( num_cpus=args.ray_num_cpus or 1, num_gpus=args.ray_num_gpus or",
"for exp in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] = True if",
"obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"pol_\" +",
"TODO should be in exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file exp['loggers']",
"n_cpu = multiprocessing.cpu_count() import tensorflow as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU'))",
"as ray_results import yaml from gym.spaces import Tuple from ray.cluster_utils",
"related configs if eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove",
"= True if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if run_args.v: exp[\"config\"][\"log_level\"]",
"or 1, object_store_memory=args.ray_object_store_memory, memory=args.ray_memory, redis_max_memory=args.ray_redis_max_memory) ray.init(address=cluster.address) else: import multiprocessing n_cpu",
"agent_id: \"pol_\" + str(agent_id)} def setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple",
"exp['config'].get('env_config') eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config: # We",
"\", n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \", args.ray_num_gpus)",
"{ run_args.experiment_name: { # i.e. log to ~/ray_results/default \"run\": run_args.run,",
"None: experiments, verbose = self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp) if",
"make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from",
"\"INFO\" verbose = 2 if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose",
"add evaluation config to the current config exp['config'] = merge_dicts(exp['config'],",
"ray import ray.tune.result as ray_results import yaml from gym.spaces import",
"# TODO should be in exp['config'] directly exp['config']['env_config']['yaml_config'] = args.config_file",
"\"policy_mapping_fn\": lambda agent_id: \"meta\" if 'meta' in str(agent_id) else \"agent\"",
"if run_args.bind_all: webui_host = \"0.0.0.0\" if run_args.log_flatland_stats: exp['config']['callbacks'] = {",
"AVAILABLE: \", n_gpu) print(\"NUM_CPUS ARGS: \", args.ray_num_cpus) print(\"NUM_GPUS ARGS: \",",
"Tuple from ray.cluster_utils import Cluster from ray.rllib.utils import try_import_tf, try_import_torch",
"if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\"",
"\", args.ray_num_gpus) ray.init( local_mode=True if args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory,",
"del eval_env_config['wandb'] # Remove any wandb related configs if exp['config']['evaluation_config'].get('wandb'):",
"eval_env_config = exp['config']['evaluation_config'].get('env_config') if eval_seed and eval_env_config: # We override",
"= str(input_file) if exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] ==",
"else: import multiprocessing n_cpu = multiprocessing.cpu_count() import tensorflow as tf",
"def apply_args(self, run_args, experiments: dict): verbose = 1 webui_host =",
"num_gpus=args.ray_num_gpus if args.ray_num_gpus is not None else n_gpu) run_experiments( experiments,",
"if eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove any wandb related configs",
"exp[\"config\"][\"eager\"] = True if run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if run_args.v:",
"{}), \"agent\": (None, obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda agent_id:",
"os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent input_file = rllib_dir.absolute().joinpath(exp[\"config\"][\"input\"]) exp[\"config\"][\"input\"] = str(input_file)",
"arguments are required: --run\") if not exp.get(\"envs\") and not exp.get(\"config\",",
"open(run_args.config_file) as f: experiments = yaml.safe_load(f) else: experiments = {",
"flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing import FillingFlatlandGymEnv from flatlander.logging.custom_metrics import",
"local_mode=True if args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus",
"else \"agent\" } def apply_args(self, run_args, experiments: dict): verbose =",
"# Remove any wandb related configs if eval_env_config: if eval_env_config.get('wandb'):",
"TBXLogger from ray.tune.resources import resources_to_json from ray.tune.tune import _make_scheduler from",
"are required: --run\") if not exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"):",
"\"..\", \"..\", \"..\", \"flatland-challenge-data/results\") class ExperimentRunner: group_algorithms = [\"QMIX\", \"QMIXApex\"]",
"from ray.cluster_utils import Cluster from ray.rllib.utils import try_import_tf, try_import_torch from",
"run_args.trace: if not exp[\"config\"].get(\"eager\"): raise ValueError(\"Must enable --eager to enable",
"dict, args=None): verbose = 1 webui_host = \"localhost\" for exp",
"= make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"pol_\" + str(i):",
"if eval_env_config: if eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove any wandb",
"not None else n_cpu, num_gpus=args.ray_num_gpus if args.ray_num_gpus is not None",
"= eval_seed # Remove any wandb related configs if eval_env_config:",
"object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is not None else n_cpu, num_gpus=args.ray_num_gpus",
"range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env( \"flatland_sparse_grouped\",",
"run_args.torch: exp[\"config\"][\"use_pytorch\"] = True if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose",
"\"num_samples\": run_args.num_samples, \"upload_dir\": run_args.upload_dir, } } if arg_parser is not",
"exp[\"run\"] in self.group_algorithms: self.setup_grouping(exp.get(\"config\")) if exp[\"run\"] == \"contrib/MADDPG\" or exp[\"config\"].get(\"individual_policies\",",
"WandbLogger from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\",",
"or exp[\"config\"].get(\"individual_policies\", False): self.setup_policy_map(exp.get(\"config\")) if exp[\"config\"].get(\"individual_policies\", False): del exp[\"config\"][\"individual_policies\"] if",
"= [WandbLogger, TBXLogger] if args.ray_num_nodes: cluster = Cluster() for _",
"setup_hierarchical_policies(self, config: dict): obs_space: gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] =",
"in experiments.values(): if not exp.get(\"run\"): arg_parser.error(\"the following arguments are required:",
"100 exp.get(\"config\")[\"env_config\"][\"actions_are_logits\"] = True if exp[\"env\"] == \"flatland_sparse_hierarchical\": self.setup_hierarchical_policies(exp.get(\"config\")) if",
"gym.spaces.Tuple = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\": {\"meta\": (None,",
"{}).get('env_config', {}).get('seed') # add evaluation config to the current config",
"def setup_grouping(config: dict): grouping = { \"group_1\": list(range(config[\"env_config\"][\"max_n_agents\"])), } obs_space",
"from flatlander.utils.loader import load_envs, load_models ray_results.DEFAULT_RESULTS_DIR = os.path.join(os.getcwd(), \"..\", \"..\",",
"obs_space.spaces[1], FillingFlatlandGymEnv.action_space, {}) }, \"policy_mapping_fn\": lambda agent_id: \"meta\" if 'meta'",
"exp[\"config\"][\"use_pytorch\"] = True if run_args.v: exp[\"config\"][\"log_level\"] = \"INFO\" verbose =",
"if run_args.log_flatland_stats: exp['config']['callbacks'] = { 'on_episode_end': on_episode_end, } return experiments,",
"in experiments.values(): if run_args.eager: exp[\"config\"][\"eager\"] = True if run_args.torch: exp[\"config\"][\"use_pytorch\"]",
"( run_args.resources_per_trial and resources_to_json(run_args.resources_per_trial)), \"stop\": run_args.stop, \"config\": dict(run_args.config, env=run_args.env), \"restore\":",
"config: dict): obs_space = make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() config[\"multiagent\"] = { \"policies\":",
"FillingFlatlandGymEnv.action_space, {\"agent_id\": i}) for i in range(config[\"env_config\"][\"observation_config\"][\"max_n_agents\"])}, \"policy_mapping_fn\": lambda agent_id:",
"in range(config[\"env_config\"][\"max_n_agents\"])]) act_space = Tuple([GlobalFlatlandGymEnv.action_space for _ in range(config[\"env_config\"][\"max_n_agents\"])]) register_env(",
"not isinstance(exp.get(\"config\", {}).get(\"input\"), dict): if not os.path.exists(exp[\"config\"][\"input\"]): rllib_dir = Path(__file__).parent",
"argparse import ArgumentParser from pathlib import Path import gym import",
"obs_space = Tuple([make_obs(config[\"env_config\"][\"observation\"], config[\"env_config\"][\"observation_config\"]).observation_space() for _ in range(config[\"env_config\"][\"max_n_agents\"])]) act_space =",
"if args.local else False, address=args.ray_address, object_store_memory=args.ray_object_store_memory, num_cpus=args.ray_num_cpus if args.ray_num_cpus is",
"eval_env_config.get('wandb'): del eval_env_config['wandb'] # Remove any wandb related configs if",
"= multiprocessing.cpu_count() import tensorflow as tf n_gpu = len(tf.config.experimental.list_physical_devices('GPU')) print(\"NUM_CPUS",
"on_episode_end from flatlander.logging.wandb_logger import WandbLogger from flatlander.utils.loader import load_envs, load_models",
"= [\"QMIX\", \"QMIXApex\"] def __init__(self): self.tf = try_import_tf() self.torch, _",
"experiments, verbose = self.apply_args(run_args=args, experiments=experiments) if args.eval: self.evaluate(exp) if args.config_file:",
"from flatlander.envs.observations import make_obs from flatlander.envs.utils.global_gym_env import GlobalFlatlandGymEnv from flatlander.envs.utils.gym_env_fill_missing",
"get_eval_config(exp['config'].get('env_config', {}).get('eval_generator', \"default\")) eval_seed = eval_configs.get('evaluation_config', {}).get('env_config', {}).get('seed') # add",
"\"flatland_sparse_grouped\", lambda config: FlatlandSparse(config).with_agent_groups( grouping, obs_space=obs_space, act_space=act_space)) def setup_policy_map(self, config:",
"exp.get(\"envs\") and not exp.get(\"config\", {}).get(\"envs\"): arg_parser.error(\"the following arguments are required:",
"__init__(self): self.tf = try_import_tf() self.torch, _ = try_import_torch() load_envs(os.path.dirname(__file__)) load_models(os.path.dirname(__file__))",
"evaluation config eval_env_config['seed'] = eval_seed # Remove any wandb related",
"verbose = 2 if run_args.vv: exp[\"config\"][\"log_level\"] = \"DEBUG\" verbose =",
"\"run\": run_args.run, \"checkpoint_freq\": run_args.checkpoint_freq, \"keep_checkpoints_num\": run_args.keep_checkpoints_num, \"checkpoint_score_attr\": run_args.checkpoint_score_attr, \"local_dir\": run_args.local_dir,"
] |
[
"No:Not Available Location:Not Available FRU Number:Not Available Device:Not Available Error",
"'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part No': 'Not",
"'Not Available', 'Device': 'Not Available', 'FRU Number': 'Not Available', 'Location':",
"'/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped on error', 'Exerciser Name':",
"output string and return list of strings in the form",
"EMPTY and increment index count. temp_error_dict = {} error_index +=",
"name, *args): r\"\"\" Execute a robot keyword repeatedly until it",
"as success. elif time.time() > timeout > 0: BuiltIn().log(\"Max retry",
"log output string and return list of strings in the",
"> 0: BuiltIn().log(\"Max retry timeout\") return True time.sleep(interval) BuiltIn().log(time.time()) return",
"# Set temp error list to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list)",
"expected\") return False # Return if retry timeout as success.",
"for entry_list in error_list: # Loop through the first error",
"entry in entry_list: # Split string into list for key",
"# Convert the retry time in seconds retry_seconds = DateTime.convert_time(retry)",
"= 0039 from file , line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device",
"Available', 'FRU Number': 'Not Available', 'Location': 'Not Available', 'Device id':",
"{} temp_error_dict = {} error_index = 0 # Loop through",
"# Loop through the error list. for entry_list in error_list:",
"in functions and use in test where generic robot keywords",
"error', 'Exerciser Name': 'hxenvidia' } }, \"\"\" # List which",
"int(retry_seconds) # Convert the interval time in seconds interval_seconds =",
"'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent returned err",
"while True: status = BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords",
"on error', 'Exerciser Name': 'hxenvidia' } }, \"\"\" # List",
"= 0039 from file , line 430.', 'Exerciser Name': 'hxenvidia'",
"# Loop through the first error list entry. for entry",
"from file , line 430.'] \"\"\" # List which will",
"parse_walk = True continue # Mark line starting with \"-\"",
"in minute(s) for looping. name Robot keyword to execute. args",
"if line.startswith(\"#\"): continue # Mark line starting with \"-\" and",
"entry. error_dict = {} temp_error_dict = {} error_index = 0",
"running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29",
"index. error_dict[error_index] = temp_error_dict # Reset temp dict to EMPTY",
"'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent returned err = 0039",
"keywords returns as failure. if status is False: BuiltIn().log(\"Failed as",
"id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial",
"\"#\" if line.startswith(\"#\"): continue # Mark line starting with \"-\"",
"'err=00000027' parm_split = re.split(\"[:=]\", entry) # Populate temp dictionary with",
"return True time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output):",
"error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which holds the error dictionry",
"strings in the form \"<field name>:<field value>\". The output of",
"elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False temp_error_list = [] #",
", line 430.'] \"\"\" # List which will hold all",
"output dictionary: { 0: { 'sev': '1', 'err': '00000027', 'Timestamp':",
"list of dictionary entries. Description of argument(s): error_list Error list",
"in entry_list: # Split string into list for key value",
"the master dictionary per entry index. error_dict[error_index] = temp_error_dict #",
"Available', 'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent returned",
"reset parse flag. # Set temp error list to EMPTY.",
"'FRU Number': 'Not Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0',",
"retry_seconds = DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds) # Convert",
"Exerciser stopped on error', 'Exerciser Name': 'hxenvidia' } }, \"\"\"",
"robot.libraries import DateTime import re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name,",
"seconds interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while",
"Return if keywords returns as failure. if status is False:",
"with \"-\" and set parse flag. if line.startswith(\"-\") and parse_walk",
"2017', 'Part No': 'Not Available', 'Serial No': 'Not Available', 'Device':",
"status = BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords returns as",
"string and return list of strings in the form \"<field",
"contains keyword functions to supplement robot's built in functions and",
"'hxenvidia' }, 1: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar",
"1: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54",
"Return if retry timeout as success. elif time.time() > timeout",
"build_error_dict function. Description of argument(s): htx_error_log_output Error entry string containing",
"Skip lines starting with \"#\" if line.startswith(\"#\"): continue # Mark",
"value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the master",
"temp error list to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk =",
"the interval time in seconds interval_seconds = DateTime.convert_time(retry_interval) interval =",
"Available Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from",
"Available', 'Part No:Not Available', 'Location:Not Available', 'FRU Number:Not Available', 'Device:Not",
"\"\"\" # List which will hold all the list of",
"# Update the master dictionary per entry index. error_dict[error_index] =",
"the first error list entry. for entry in entry_list: #",
"'00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part No': 'Not Available',",
"err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part No:Not Available",
"with key value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update",
"repeatedly until it either fails or the timeout value is",
"time from robot.libraries.BuiltIn import BuiltIn from robot.libraries import DateTime import",
"Available', 'Device id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped on",
"0039 from file , line 430.'] \"\"\" # List which",
"string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027',",
"Mark line starting with \"-\" and set parse flag. if",
"time in seconds interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout)",
"in seconds retry_seconds = DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds)",
"and set parse flag. if line.startswith(\"-\") and parse_walk is False:",
"time in hour(s). retry_interval Time interval in minute(s) for looping.",
"parse flag. # Set temp error list to EMPTY. elif",
"Name': 'hxenvidia' } }, \"\"\" # List which will hold",
"retry time in seconds retry_seconds = DateTime.convert_time(retry) timeout = time.time()",
"with \"-\" and reset parse flag. # Set temp error",
"temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds error",
"Parse htx error log output string and return list of",
"list to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False temp_error_list",
"line 430.'] \"\"\" # List which will hold all the",
"retry_interval Time interval in minute(s) for looping. name Robot keyword",
"dictionary entries. Description of argument(s): error_list Error list entries. Example",
"import DateTime import re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args):",
"\"Wait Until Keyword Succeeds\". Description of argument(s): retry Max timeout",
"Mark line starting with \"-\" and reset parse flag. #",
"time.time() + int(retry_seconds) # Convert the interval time in seconds",
"Number:Not Available Device:Not Available Error Text:cudaEventSynchronize for stopEvent returned err",
"exceeded. Note: Opposite of robot keyword \"Wait Until Keyword Succeeds\".",
"dictionary which holds the error dictionry entry. error_dict = {}",
"Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split = re.split(\"[:=]\", entry)",
"output of this function may be passed to the build_error_dict",
"'Serial No:Not Available', 'Part No:Not Available', 'Location:Not Available', 'FRU Number:Not",
"############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error log output",
"error_list.append(temp_error_list) parse_walk = False temp_error_list = [] # Add entry",
"re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\" Execute a",
"seconds retry_seconds = DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds) #",
"and reset parse flag. # Set temp error list to",
"'Not Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text':",
"Convert the interval time in seconds interval_seconds = DateTime.convert_time(retry_interval) interval",
"is exceeded. Note: Opposite of robot keyword \"Wait Until Keyword",
"Available Location:Not Available FRU Number:Not Available Device:Not Available Error Text:Hardware",
"of robot keyword \"Wait Until Keyword Succeeds\". Description of argument(s):",
"Part No:Not Available Location:Not Available FRU Number:Not Available Device:Not Available",
"a list of dictionary entries. Description of argument(s): error_list Error",
"returns as failure. if status is False: BuiltIn().log(\"Failed as expected\")",
"id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped on error', 'Exerciser",
"Number:Not Available Device:Not Available Error Text:Hardware Exerciser stopped on error",
"form \"<field name>:<field value>\". The output of this function may",
"Name:hxenvidia Serial No:Not Available Part No:Not Available Location:Not Available FRU",
"= DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status",
"timeout value is exceeded. Note: Opposite of robot keyword \"Wait",
"is False: BuiltIn().log(\"Failed as expected\") return False # Return if",
"error list entry. for entry in entry_list: # Split string",
"the retry time in seconds retry_seconds = DateTime.convert_time(retry) timeout =",
"timeout > 0: BuiltIn().log(\"Max retry timeout\") return True time.sleep(interval) BuiltIn().log(time.time())",
"line in htx_error_log_output.splitlines(): # Skip lines starting with \"#\" if",
"interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True:",
"value update. # Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split",
"of argument(s): retry Max timeout time in hour(s). retry_interval Time",
"a robot keyword repeatedly until it either fails or the",
"keyword to execute. args Robot keyword arguments. \"\"\" # Convert",
"entries. Example output dictionary: { 0: { 'sev': '1', 'err':",
"#!/usr/bin/env python r\"\"\" This module contains keyword functions to supplement",
"for looping. name Robot keyword to execute. args Robot keyword",
"'Not Available', 'Serial No': 'Not Available', 'Device': 'Not Available', 'FRU",
"returned err = 0039 from file , line 430.'] \"\"\"",
"line starting with \"-\" and set parse flag. if line.startswith(\"-\")",
"# Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split = re.split(\"[:=]\",",
"Populate temp dictionary with key value pair data. temp_error_dict[str(parm_split[0])] =",
"argument(s): htx_error_log_output Error entry string containing the stdout generated by",
"retry timeout as success. elif time.time() > timeout > 0:",
"/usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027",
"temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the master dictionary per entry",
"Ends Here ################################ Example output: Returns the lists of error",
"string into list for key value update. # Example: 'Device",
"entry string containing the stdout generated by \"htxcmdline -geterrlog\". Example",
"flag. if line.startswith(\"-\") and parse_walk is False: parse_walk = True",
"# Convert the interval time in seconds interval_seconds = DateTime.convert_time(retry_interval)",
"of argument(s): error_list Error list entries. Example output dictionary: {",
"29 19:41:54 2017', 'Part No': 'Not Available', 'Serial No': 'Not",
"entries. Description of argument(s): error_list Error list entries. Example output",
"Error entry string containing the stdout generated by \"htxcmdline -geterrlog\".",
"Available', 'Location:Not Available', 'FRU Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize",
"where generic robot keywords don't support. \"\"\" import time from",
"argument(s): retry Max timeout time in hour(s). retry_interval Time interval",
"Device:Not Available Error Text:Hardware Exerciser stopped on error --------------------------------------------------------------------- #########################",
"# Example: 'err=00000027' parm_split = re.split(\"[:=]\", entry) # Populate temp",
"the form \"<field name>:<field value>\". The output of this function",
"for line in htx_error_log_output.splitlines(): # Skip lines starting with \"#\"",
"return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error",
"error --------------------------------------------------------------------- ######################### Result Ends Here ################################ Example output: Returns",
"name>:<field value>\". The output of this function may be passed",
"The output of this function may be passed to the",
"into a list of dictionary entries. Description of argument(s): error_list",
"+ int(retry_seconds) # Convert the interval time in seconds interval_seconds",
"= [] # Add entry to list if line is",
"flag. # Set temp error list to EMPTY. elif line.startswith(\"-\"):",
"argument(s): error_list Error list entries. Example output dictionary: { 0:",
"'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not Available',",
"line is not emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list ###############################################################################",
"error_index = 0 # Loop through the error list. for",
"for entry in entry_list: # Split string into list for",
"Result Starts Here ############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit ===========================",
"dictionry entry. error_dict = {} temp_error_dict = {} error_index =",
"# Skip lines starting with \"#\" if line.startswith(\"#\"): continue #",
"'Part No': 'Not Available', 'Serial No': 'Not Available', 'Device': 'Not",
"starting with \"-\" and reset parse flag. # Set temp",
"Keyword Succeeds\". Description of argument(s): retry Max timeout time in",
"arguments. \"\"\" # Convert the retry time in seconds retry_seconds",
"r\"\"\" Parse htx error log output string and return list",
"key value update. # Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027'",
"either fails or the timeout value is exceeded. Note: Opposite",
"Example: 'err=00000027' parm_split = re.split(\"[:=]\", entry) # Populate temp dictionary",
", line 430.', 'Exerciser Name': 'hxenvidia' }, 1: { 'sev':",
"2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not",
"parm_split[1] # Update the master dictionary per entry index. error_dict[error_index]",
"430.', 'Exerciser Name': 'hxenvidia' }, 1: { 'sev': '1', 'err':",
"False: BuiltIn().log(\"Failed as expected\") return False # Return if retry",
"the stdout generated by \"htxcmdline -geterrlog\". Example of htx_error_log_output contents:",
"Description of argument(s): error_list Error list entries. Example output dictionary:",
"module contains keyword functions to supplement robot's built in functions",
"Serial No:Not Available Part No:Not Available Location:Not Available FRU Number:Not",
"list of strings in the form \"<field name>:<field value>\". The",
"may be passed to the build_error_dict function. Description of argument(s):",
"interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name,",
"-geterrlog\". Example of htx_error_log_output contents: ######################## Result Starts Here ###############################",
"################################ Example output: Returns the lists of error string per",
"True: status = BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords returns",
"This module contains keyword functions to supplement robot's built in",
"Available', 'Serial No': 'Not Available', 'Device': 'Not Available', 'FRU Number':",
"Split string into list for key value update. # Example:",
"Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not",
"= 0039 from file , line 430.'] \"\"\" # List",
"test where generic robot keywords don't support. \"\"\" import time",
"and parse_walk is False: parse_walk = True continue # Mark",
"as expected\") return False # Return if retry timeout as",
"Name': 'hxenvidia' }, 1: { 'sev': '1', 'err': '00000027', 'Timestamp':",
"ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54",
"############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error log output string",
"all the list of entries. error_list = [] error_list =",
"= [] temp_error_list = [] parse_walk = False for line",
"python r\"\"\" This module contains keyword functions to supplement robot's",
"robot keyword repeatedly until it either fails or the timeout",
"error_list Error list entries. Example output dictionary: { 0: {",
"int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name, *args) #",
"True continue # Mark line starting with \"-\" and reset",
"import time from robot.libraries.BuiltIn import BuiltIn from robot.libraries import DateTime",
"entry_list: # Split string into list for key value update.",
", line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54",
"minute(s) for looping. name Robot keyword to execute. args Robot",
"in the form \"<field name>:<field value>\". The output of this",
"Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not Available', 'Location:Not Available', 'FRU",
"parse_walk is False: parse_walk = True continue # Mark line",
"run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\" Execute a robot keyword repeatedly",
"set parse flag. if line.startswith(\"-\") and parse_walk is False: parse_walk",
"is False: parse_walk = True continue # Mark line starting",
"dictionary per entry index. error_dict[error_index] = temp_error_dict # Reset temp",
"\"htxcmdline -geterrlog\". Example of htx_error_log_output contents: ######################## Result Starts Here",
"430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027",
"line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017",
"BuiltIn from robot.libraries import DateTime import re ############################################################################### def run_until_keyword_fails(retry,",
"of dictionary entries. Description of argument(s): error_list Error list entries.",
"continue # Mark line starting with \"-\" and reset parse",
"htx_error_log_output.splitlines(): # Skip lines starting with \"#\" if line.startswith(\"#\"): continue",
"starting with \"-\" and set parse flag. if line.startswith(\"-\") and",
"'Device': 'Not Available', 'FRU Number': 'Not Available', 'Location': 'Not Available',",
"robot.libraries.BuiltIn import BuiltIn from robot.libraries import DateTime import re ###############################################################################",
"error list. for entry_list in error_list: # Loop through the",
"id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial",
"EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False temp_error_list = []",
"pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the master dictionary",
"'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped",
"from robot.libraries import DateTime import re ############################################################################### def run_until_keyword_fails(retry, retry_interval,",
"list. for entry_list in error_list: # Loop through the first",
"timeout\") return True time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def",
"from robot.libraries.BuiltIn import BuiltIn from robot.libraries import DateTime import re",
"= BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords returns as failure.",
"for stopEvent returned err = 0039 from file , line",
"\"<field name>:<field value>\". The output of this function may be",
"master dictionary per entry index. error_dict[error_index] = temp_error_dict # Reset",
"value>\". The output of this function may be passed to",
"'Mar 29 19:41:54 2017', 'Part No': 'Not Available', 'Serial No':",
"interval time in seconds interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds)",
"lines starting with \"#\" if line.startswith(\"#\"): continue # Mark line",
"not emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def",
"of entries. error_list = [] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary",
"= int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name, *args)",
": /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017",
"# List which will hold all the list of entries.",
"r\"\"\" Builds error list into a list of dictionary entries.",
"the error dictionry entry. error_dict = {} temp_error_dict = {}",
"count. temp_error_dict = {} error_index += 1 return error_dict ###############################################################################",
"2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part No:Not",
"dict to EMPTY and increment index count. temp_error_dict = {}",
"Example of htx_error_log_output contents: ######################## Result Starts Here ############################### Currently",
"# dictionary which holds the error dictionry entry. error_dict =",
"in htx_error_log_output.splitlines(): # Skip lines starting with \"#\" if line.startswith(\"#\"):",
"'Error Text': 'Hardware Exerciser stopped on error', 'Exerciser Name': 'hxenvidia'",
"[] parse_walk = False for line in htx_error_log_output.splitlines(): # Skip",
"line 430.', 'Exerciser Name': 'hxenvidia' }, 1: { 'sev': '1',",
"of entries. error_list = [] temp_error_list = [] parse_walk =",
"stopEvent returned err = 0039 from file , line 430.']",
"Starts Here ############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== ---------------------------------------------------------------------",
"keyword arguments. \"\"\" # Convert the retry time in seconds",
"Until Keyword Succeeds\". Description of argument(s): retry Max timeout time",
"in error_list: # Loop through the first error list entry.",
"# Split string into list for key value update. #",
"Example output dictionary: { 0: { 'sev': '1', 'err': '00000027',",
"error_list = [] temp_error_list = [] parse_walk = False for",
"htx_error_log_output contents: ######################## Result Starts Here ############################### Currently running ECG/MDT",
"# Populate temp dictionary with key value pair data. temp_error_dict[str(parm_split[0])]",
"'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for",
"the list of entries. error_list = [] error_list = htx_error_log_to_list(htx_error_log_output)",
"Returns the lists of error string per entry ['Device id:/dev/nvidia0',",
"'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split = re.split(\"[:=]\", entry) #",
"in hour(s). retry_interval Time interval in minute(s) for looping. name",
"Available', 'Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from",
"0: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54",
"error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds error list into",
"returned err = 0039 from file , line 430.', 'Exerciser",
"continue # Mark line starting with \"-\" and set parse",
"parse flag. if line.startswith(\"-\") and parse_walk is False: parse_walk =",
"success. elif time.time() > timeout > 0: BuiltIn().log(\"Max retry timeout\")",
"the lists of error string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar",
"False temp_error_list = [] # Add entry to list if",
"is not emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ###############################################################################",
"Text:Hardware Exerciser stopped on error --------------------------------------------------------------------- ######################### Result Ends Here",
"as failure. if status is False: BuiltIn().log(\"Failed as expected\") return",
"list if line is not emtpy elif parse_walk: temp_error_list.append(str(line)) return",
"} }, \"\"\" # List which will hold all the",
"# Reset temp dict to EMPTY and increment index count.",
"List which will hold all the list of entries. error_list",
"time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse",
"if status is False: BuiltIn().log(\"Failed as expected\") return False #",
"<filename>syslib/utils_keywords.py<gh_stars>1-10 #!/usr/bin/env python r\"\"\" This module contains keyword functions to",
"No:Not Available', 'Location:Not Available', 'FRU Number:Not Available', 'Device:Not Available', 'Error",
"from file , line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar",
"index count. temp_error_dict = {} error_index += 1 return error_dict",
"htx_error_log_output Error entry string containing the stdout generated by \"htxcmdline",
"temp_error_list = [] # Add entry to list if line",
"increment index count. temp_error_dict = {} error_index += 1 return",
"line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False temp_error_list = [] # Add",
"BuiltIn().log(timeout) BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name, *args) # Return",
"= DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds) # Convert the",
"'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser",
"to supplement robot's built in functions and use in test",
"{} error_index = 0 # Loop through the error list.",
"error_list: # Loop through the first error list entry. for",
"fails or the timeout value is exceeded. Note: Opposite of",
"line.startswith(\"-\") and parse_walk is False: parse_walk = True continue #",
"'1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part No':",
"Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia",
"}, \"\"\" # List which will hold all the list",
"Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent returned err =",
"error_dict[error_index] = temp_error_dict # Reset temp dict to EMPTY and",
"DateTime import re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\"",
"Available Device:Not Available Error Text:cudaEventSynchronize for stopEvent returned err =",
"all the list of entries. error_list = [] temp_error_list =",
"Text': 'Hardware Exerciser stopped on error', 'Exerciser Name': 'hxenvidia' }",
"retry timeout\") return True time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ###############################################################################",
"lists of error string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29",
"entries. error_list = [] temp_error_list = [] parse_walk = False",
"htx_error_log_to_list(htx_error_log_output) # dictionary which holds the error dictionry entry. error_dict",
"to EMPTY and increment index count. temp_error_dict = {} error_index",
"r\"\"\" Execute a robot keyword repeatedly until it either fails",
"will hold all the list of entries. error_list = []",
"= False for line in htx_error_log_output.splitlines(): # Skip lines starting",
"Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar",
"looping. name Robot keyword to execute. args Robot keyword arguments.",
"error string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017',",
"if keywords returns as failure. if status is False: BuiltIn().log(\"Failed",
"Loop through the first error list entry. for entry in",
"keyword \"Wait Until Keyword Succeeds\". Description of argument(s): retry Max",
"Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent returned err",
"Reset temp dict to EMPTY and increment index count. temp_error_dict",
"to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False temp_error_list =",
"error_list = [] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which holds",
"[] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which holds the error",
"Here ################################ Example output: Returns the lists of error string",
"DateTime.convert_time(retry) timeout = time.time() + int(retry_seconds) # Convert the interval",
"'Part No:Not Available', 'Location:Not Available', 'FRU Number:Not Available', 'Device:Not Available',",
"Loop through the error list. for entry_list in error_list: #",
"list into a list of dictionary entries. Description of argument(s):",
"function may be passed to the build_error_dict function. Description of",
"'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent",
"which holds the error dictionry entry. error_dict = {} temp_error_dict",
"temp_error_dict = {} error_index = 0 # Loop through the",
"\"\"\" # Convert the retry time in seconds retry_seconds =",
"entry to list if line is not emtpy elif parse_walk:",
"by \"htxcmdline -geterrlog\". Example of htx_error_log_output contents: ######################## Result Starts",
"Available', 'Device': 'Not Available', 'FRU Number': 'Not Available', 'Location': 'Not",
"0039 from file , line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0",
"err = 0039 from file , line 430.'] \"\"\" #",
"generic robot keywords don't support. \"\"\" import time from robot.libraries.BuiltIn",
"parse_walk = False for line in htx_error_log_output.splitlines(): # Skip lines",
"passed to the build_error_dict function. Description of argument(s): htx_error_log_output Error",
"Available Error Text:Hardware Exerciser stopped on error --------------------------------------------------------------------- ######################### Result",
"temp dict to EMPTY and increment index count. temp_error_dict =",
"29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available',",
"for key value update. # Example: 'Device id:/dev/nvidia0' # Example:",
"BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx",
"Set temp error list to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk",
"'Error Text': 'cudaEventSynchronize for stopEvent returned err = 0039 from",
"}, 1: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29",
"temp_error_list = [] parse_walk = False for line in htx_error_log_output.splitlines():",
"and increment index count. temp_error_dict = {} error_index += 1",
"# Return if keywords returns as failure. if status is",
"*args) # Return if keywords returns as failure. if status",
"entries. error_list = [] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which",
"No:Not Available', 'Part No:Not Available', 'Location:Not Available', 'FRU Number:Not Available',",
"if retry timeout as success. elif time.time() > timeout >",
"# Return if retry timeout as success. elif time.time() >",
"0: BuiltIn().log(\"Max retry timeout\") return True time.sleep(interval) BuiltIn().log(time.time()) return True",
"= {} temp_error_dict = {} error_index = 0 # Loop",
"on error --------------------------------------------------------------------- ######################### Result Ends Here ################################ Example output:",
"into list for key value update. # Example: 'Device id:/dev/nvidia0'",
"import re ############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\" Execute",
"stopEvent returned err = 0039 from file , line 430.',",
"elif parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\"",
"'FRU Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent returned",
"and return list of strings in the form \"<field name>:<field",
"dictionary: { 0: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar",
"error list into a list of dictionary entries. Description of",
"hold all the list of entries. error_list = [] temp_error_list",
"'/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent returned err = 0039",
"Result Ends Here ################################ Example output: Returns the lists of",
"{ 0: { 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29",
"True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error log",
"True time.sleep(interval) BuiltIn().log(time.time()) return True ############################################################################### ############################################################################### def htx_error_log_to_list(htx_error_log_output): r\"\"\"",
"from file , line 430.', 'Exerciser Name': 'hxenvidia' }, 1:",
"############################################################################### def run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\" Execute a robot",
"Available FRU Number:Not Available Device:Not Available Error Text:Hardware Exerciser stopped",
"parm_split = re.split(\"[:=]\", entry) # Populate temp dictionary with key",
"stopped on error --------------------------------------------------------------------- ######################### Result Ends Here ################################ Example",
"it either fails or the timeout value is exceeded. Note:",
"dictionary with key value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] #",
"\"-\" and reset parse flag. # Set temp error list",
"Location:Not Available FRU Number:Not Available Device:Not Available Error Text:Hardware Exerciser",
"list for key value update. # Example: 'Device id:/dev/nvidia0' #",
"Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'Hardware",
"entry_list in error_list: # Loop through the first error list",
"name Robot keyword to execute. args Robot keyword arguments. \"\"\"",
"stdout generated by \"htxcmdline -geterrlog\". Example of htx_error_log_output contents: ########################",
"build_error_dict(htx_error_log_output): r\"\"\" Builds error list into a list of dictionary",
"19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part",
"=========================== --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1",
"file , line 430. --------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29",
"time in seconds retry_seconds = DateTime.convert_time(retry) timeout = time.time() +",
"emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output):",
"elif time.time() > timeout > 0: BuiltIn().log(\"Max retry timeout\") return",
"return False # Return if retry timeout as success. elif",
"BuiltIn().log(\"Max retry timeout\") return True time.sleep(interval) BuiltIn().log(time.time()) return True ###############################################################################",
"first error list entry. for entry in entry_list: # Split",
"Description of argument(s): retry Max timeout time in hour(s). retry_interval",
"Robot keyword arguments. \"\"\" # Convert the retry time in",
"through the first error list entry. for entry in entry_list:",
"No': 'Not Available', 'Device': 'Not Available', 'FRU Number': 'Not Available',",
"['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia',",
"id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize for stopEvent returned err =",
"parse_walk: temp_error_list.append(str(line)) return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds",
"line starting with \"-\" and reset parse flag. # Set",
"\"\"\" import time from robot.libraries.BuiltIn import BuiltIn from robot.libraries import",
"def run_until_keyword_fails(retry, retry_interval, name, *args): r\"\"\" Execute a robot keyword",
"'Serial No': 'Not Available', 'Device': 'Not Available', 'FRU Number': 'Not",
"entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser",
"r\"\"\" This module contains keyword functions to supplement robot's built",
"until it either fails or the timeout value is exceeded.",
"Available FRU Number:Not Available Device:Not Available Error Text:cudaEventSynchronize for stopEvent",
"entry) # Populate temp dictionary with key value pair data.",
"= parm_split[1] # Update the master dictionary per entry index.",
"file , line 430.'] \"\"\" # List which will hold",
"in test where generic robot keywords don't support. \"\"\" import",
"430.'] \"\"\" # List which will hold all the list",
"= htx_error_log_to_list(htx_error_log_output) # dictionary which holds the error dictionry entry.",
"parse_walk = False temp_error_list = [] # Add entry to",
"which will hold all the list of entries. error_list =",
"value is exceeded. Note: Opposite of robot keyword \"Wait Until",
"to execute. args Robot keyword arguments. \"\"\" # Convert the",
"Available Location:Not Available FRU Number:Not Available Device:Not Available Error Text:cudaEventSynchronize",
"support. \"\"\" import time from robot.libraries.BuiltIn import BuiltIn from robot.libraries",
"'Device id': '/dev/nvidia0', 'Error Text': 'Hardware Exerciser stopped on error',",
"BuiltIn().log(interval) while True: status = BuiltIn().run_keyword_and_return_status(name, *args) # Return if",
"if line.startswith(\"-\") and parse_walk is False: parse_walk = True continue",
"entry index. error_dict[error_index] = temp_error_dict # Reset temp dict to",
"err = 0039 from file , line 430.', 'Exerciser Name':",
"Execute a robot keyword repeatedly until it either fails or",
"execute. args Robot keyword arguments. \"\"\" # Convert the retry",
"temp dictionary with key value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1]",
"import BuiltIn from robot.libraries import DateTime import re ############################################################################### def",
"in seconds interval_seconds = DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval)",
"[] temp_error_list = [] parse_walk = False for line in",
"Builds error list into a list of dictionary entries. Description",
"this function may be passed to the build_error_dict function. Description",
"'Location:Not Available', 'FRU Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for",
"the list of entries. error_list = [] temp_error_list = []",
"No': 'Not Available', 'Serial No': 'Not Available', 'Device': 'Not Available',",
"retry_interval, name, *args): r\"\"\" Execute a robot keyword repeatedly until",
"Convert the retry time in seconds retry_seconds = DateTime.convert_time(retry) timeout",
"of strings in the form \"<field name>:<field value>\". The output",
"Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from file",
"key value pair data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the",
"or the timeout value is exceeded. Note: Opposite of robot",
"= [] parse_walk = False for line in htx_error_log_output.splitlines(): #",
"string containing the stdout generated by \"htxcmdline -geterrlog\". Example of",
"############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device id:/dev/nvidia0",
"= time.time() + int(retry_seconds) # Convert the interval time in",
"returned err = 0039 from file , line 430. ---------------------------------------------------------------------",
"the error list. for entry_list in error_list: # Loop through",
"Note: Opposite of robot keyword \"Wait Until Keyword Succeeds\". Description",
"# Mark line starting with \"-\" and set parse flag.",
"######################## Result Starts Here ############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit",
"time.time() > timeout > 0: BuiltIn().log(\"Max retry timeout\") return True",
"containing the stdout generated by \"htxcmdline -geterrlog\". Example of htx_error_log_output",
"--------------------------------------------------------------------- ######################### Result Ends Here ################################ Example output: Returns the",
"False # Return if retry timeout as success. elif time.time()",
"holds the error dictionry entry. error_dict = {} temp_error_dict =",
"through the error list. for entry_list in error_list: # Loop",
"error dictionry entry. error_dict = {} temp_error_dict = {} error_index",
"Error list entries. Example output dictionary: { 0: { 'sev':",
"interval in minute(s) for looping. name Robot keyword to execute.",
"htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error log output string and return",
"Exerciser stopped on error --------------------------------------------------------------------- ######################### Result Ends Here ################################",
"> timeout > 0: BuiltIn().log(\"Max retry timeout\") return True time.sleep(interval)",
"of error string per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54",
"robot keywords don't support. \"\"\" import time from robot.libraries.BuiltIn import",
"with \"#\" if line.startswith(\"#\"): continue # Mark line starting with",
"False: parse_walk = True continue # Mark line starting with",
"hold all the list of entries. error_list = [] error_list",
"of htx_error_log_output contents: ######################## Result Starts Here ############################### Currently running",
"list of entries. error_list = [] temp_error_list = [] parse_walk",
"######################### Result Ends Here ################################ Example output: Returns the lists",
"retry Max timeout time in hour(s). retry_interval Time interval in",
"Update the master dictionary per entry index. error_dict[error_index] = temp_error_dict",
"built in functions and use in test where generic robot",
"stopped on error', 'Exerciser Name': 'hxenvidia' } }, \"\"\" #",
"status is False: BuiltIn().log(\"Failed as expected\") return False # Return",
"= False temp_error_list = [] # Add entry to list",
"keyword functions to supplement robot's built in functions and use",
"error log output string and return list of strings in",
"'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not",
"of argument(s): htx_error_log_output Error entry string containing the stdout generated",
"= {} error_index = 0 # Loop through the error",
"per entry ['Device id:/dev/nvidia0', 'Timestamp:Mar 29 19:41:54 2017', 'err=00000027', 'sev=1',",
"entry. for entry in entry_list: # Split string into list",
"'Hardware Exerciser stopped on error', 'Exerciser Name': 'hxenvidia' } },",
"be passed to the build_error_dict function. Description of argument(s): htx_error_log_output",
"per entry index. error_dict[error_index] = temp_error_dict # Reset temp dict",
"use in test where generic robot keywords don't support. \"\"\"",
"error list to EMPTY. elif line.startswith(\"-\"): error_list.append(temp_error_list) parse_walk = False",
"the timeout value is exceeded. Note: Opposite of robot keyword",
"def htx_error_log_to_list(htx_error_log_output): r\"\"\" Parse htx error log output string and",
"BuiltIn().run_keyword_and_return_status(name, *args) # Return if keywords returns as failure. if",
"to the build_error_dict function. Description of argument(s): htx_error_log_output Error entry",
"FRU Number:Not Available Device:Not Available Error Text:Hardware Exerciser stopped on",
"[] # Add entry to list if line is not",
"############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds error list into a",
"error_dict = {} temp_error_dict = {} error_index = 0 #",
"Robot keyword to execute. args Robot keyword arguments. \"\"\" #",
"DateTime.convert_time(retry_interval) interval = int(interval_seconds) BuiltIn().log(timeout) BuiltIn().log(interval) while True: status =",
"contents: ######################## Result Starts Here ############################### Currently running ECG/MDT :",
"# Mark line starting with \"-\" and reset parse flag.",
"= re.split(\"[:=]\", entry) # Populate temp dictionary with key value",
"0 # Loop through the error list. for entry_list in",
"'sev=1', 'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not Available', 'Location:Not",
"'hxenvidia' } }, \"\"\" # List which will hold all",
"timeout as success. elif time.time() > timeout > 0: BuiltIn().log(\"Max",
"list entry. for entry in entry_list: # Split string into",
"Description of argument(s): htx_error_log_output Error entry string containing the stdout",
"Location:Not Available FRU Number:Not Available Device:Not Available Error Text:cudaEventSynchronize for",
"robot keyword \"Wait Until Keyword Succeeds\". Description of argument(s): retry",
"failure. if status is False: BuiltIn().log(\"Failed as expected\") return False",
"No:Not Available Part No:Not Available Location:Not Available FRU Number:Not Available",
"functions and use in test where generic robot keywords don't",
"0039 from file , line 430.', 'Exerciser Name': 'hxenvidia' },",
"timeout = time.time() + int(retry_seconds) # Convert the interval time",
"Available', 'FRU Number:Not Available', 'Device:Not Available', 'Error Text:cudaEventSynchronize for stopEvent",
"'Exerciser Name': 'hxenvidia' } }, \"\"\" # List which will",
"Number': 'Not Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error",
"19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part",
"htx error log output string and return list of strings",
"'Exerciser Name': 'hxenvidia' }, 1: { 'sev': '1', 'err': '00000027',",
"functions to supplement robot's built in functions and use in",
"keywords don't support. \"\"\" import time from robot.libraries.BuiltIn import BuiltIn",
"--------------------------------------------------------------------- --------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1",
"{ 'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017',",
"Add entry to list if line is not emtpy elif",
"robot's built in functions and use in test where generic",
"= 0 # Loop through the error list. for entry_list",
"return list of strings in the form \"<field name>:<field value>\".",
"timeout time in hour(s). retry_interval Time interval in minute(s) for",
"err = 0039 from file , line 430. --------------------------------------------------------------------- ---------------------------------------------------------------------",
"Here ############################### Currently running ECG/MDT : /usr/lpp/htx/mdt/mdt.whit =========================== --------------------------------------------------------------------- Device",
"hour(s). retry_interval Time interval in minute(s) for looping. name Robot",
"False for line in htx_error_log_output.splitlines(): # Skip lines starting with",
"'Timestamp': 'Mar 29 19:41:54 2017', 'Part No': 'Not Available', 'Serial",
"############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds error list into a list",
"\"-\" and set parse flag. if line.startswith(\"-\") and parse_walk is",
"function. Description of argument(s): htx_error_log_output Error entry string containing the",
"list of entries. error_list = [] error_list = htx_error_log_to_list(htx_error_log_output) #",
"= [] error_list = htx_error_log_to_list(htx_error_log_output) # dictionary which holds the",
"data. temp_error_dict[str(parm_split[0])] = parm_split[1] # Update the master dictionary per",
"Time interval in minute(s) for looping. name Robot keyword to",
"FRU Number:Not Available Device:Not Available Error Text:cudaEventSynchronize for stopEvent returned",
"Succeeds\". Description of argument(s): retry Max timeout time in hour(s).",
"BuiltIn().log(\"Failed as expected\") return False # Return if retry timeout",
"update. # Example: 'Device id:/dev/nvidia0' # Example: 'err=00000027' parm_split =",
"# Add entry to list if line is not emtpy",
"'Not Available', 'FRU Number': 'Not Available', 'Location': 'Not Available', 'Device",
"re.split(\"[:=]\", entry) # Populate temp dictionary with key value pair",
"Exerciser Name:hxenvidia Serial No:Not Available Part No:Not Available Location:Not Available",
"Available Device:Not Available Error Text:Hardware Exerciser stopped on error ---------------------------------------------------------------------",
"return error_list ############################################################################### ############################################################################### def build_error_dict(htx_error_log_output): r\"\"\" Builds error list",
"'Error Text:cudaEventSynchronize for stopEvent returned err = 0039 from file",
"Text': 'cudaEventSynchronize for stopEvent returned err = 0039 from file",
"if line is not emtpy elif parse_walk: temp_error_list.append(str(line)) return error_list",
"file , line 430.', 'Exerciser Name': 'hxenvidia' }, 1: {",
"Max timeout time in hour(s). retry_interval Time interval in minute(s)",
"= True continue # Mark line starting with \"-\" and",
"temp_error_dict # Reset temp dict to EMPTY and increment index",
"don't support. \"\"\" import time from robot.libraries.BuiltIn import BuiltIn from",
"Available Part No:Not Available Location:Not Available FRU Number:Not Available Device:Not",
"*args): r\"\"\" Execute a robot keyword repeatedly until it either",
"args Robot keyword arguments. \"\"\" # Convert the retry time",
"Text:cudaEventSynchronize for stopEvent returned err = 0039 from file ,",
"'Exerciser Name:hxenvidia', 'Serial No:Not Available', 'Part No:Not Available', 'Location:Not Available',",
"'cudaEventSynchronize for stopEvent returned err = 0039 from file ,",
"Available', 'Location': 'Not Available', 'Device id': '/dev/nvidia0', 'Error Text': 'cudaEventSynchronize",
"--------------------------------------------------------------------- Device id:/dev/nvidia0 Timestamp:Mar 29 19:41:54 2017 err=00000027 sev=1 Exerciser",
"to list if line is not emtpy elif parse_walk: temp_error_list.append(str(line))",
"Error Text:Hardware Exerciser stopped on error --------------------------------------------------------------------- ######################### Result Ends",
"supplement robot's built in functions and use in test where",
"list entries. Example output dictionary: { 0: { 'sev': '1',",
"line.startswith(\"#\"): continue # Mark line starting with \"-\" and set",
"Device:Not Available Error Text:cudaEventSynchronize for stopEvent returned err = 0039",
"sev=1 Exerciser Name:hxenvidia Serial No:Not Available Part No:Not Available Location:Not",
"19:41:54 2017', 'Part No': 'Not Available', 'Serial No': 'Not Available',",
"id:/dev/nvidia0' # Example: 'err=00000027' parm_split = re.split(\"[:=]\", entry) # Populate",
"keyword repeatedly until it either fails or the timeout value",
"starting with \"#\" if line.startswith(\"#\"): continue # Mark line starting",
"generated by \"htxcmdline -geterrlog\". Example of htx_error_log_output contents: ######################## Result",
"def build_error_dict(htx_error_log_output): r\"\"\" Builds error list into a list of",
"= temp_error_dict # Reset temp dict to EMPTY and increment",
"Example output: Returns the lists of error string per entry",
"of this function may be passed to the build_error_dict function.",
"and use in test where generic robot keywords don't support.",
"the build_error_dict function. Description of argument(s): htx_error_log_output Error entry string",
"'sev': '1', 'err': '00000027', 'Timestamp': 'Mar 29 19:41:54 2017', 'Part",
"output: Returns the lists of error string per entry ['Device",
"Opposite of robot keyword \"Wait Until Keyword Succeeds\". Description of",
"29 19:41:54 2017 err=00000027 sev=1 Exerciser Name:hxenvidia Serial No:Not Available",
"stopEvent returned err = 0039 from file , line 430."
] |
[
"from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode)",
"import XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode',",
"import FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode,",
"ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode from .mmpose_nodes import",
"DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__",
"from .builder import NODES from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes",
"'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode', 'SaiyanNode', 'BackgroundNode',",
"from .xdwendwen_nodes import XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode',",
"from .mmdet_nodes import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes",
"import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode",
"from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode",
"FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode,",
".xdwendwen_nodes import XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode',",
"import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes",
"= [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode',",
"[ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode',",
"MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode",
"# Copyright (c) OpenMMLab. All rights reserved. from .builder import",
"RecorderNode from .mmdet_nodes import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from",
"rights reserved. from .builder import NODES from .faceswap_nodes import FaceSwapNode",
"MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode,",
".mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__ = [",
"from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode,",
"XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode',",
"__all__ = [ 'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode',",
"import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode from .mmpose_nodes",
"'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode',",
"All rights reserved. from .builder import NODES from .faceswap_nodes import",
"OpenMMLab. All rights reserved. from .builder import NODES from .faceswap_nodes",
"'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode', 'SaiyanNode', 'BackgroundNode', 'XDwenDwenNode'",
"reserved. from .builder import NODES from .faceswap_nodes import FaceSwapNode from",
"SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes",
"'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode',",
"BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode,",
"from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__ =",
"NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode",
".helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import DetectorNode from",
"'NODES', 'PoseVisualizerNode', 'DetectorNode', 'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode',",
"(BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import",
"SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from .mmdet_nodes import",
".builder import NODES from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes import",
"'TopDownPoseEstimatorNode', 'MonitorNode', 'BugEyeNode', 'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode', 'SaiyanNode',",
"Copyright (c) OpenMMLab. All rights reserved. from .builder import NODES",
"(c) OpenMMLab. All rights reserved. from .builder import NODES from",
".frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode, PoseVisualizerNode, SaiyanNode, SunglassesNode) from",
"PoseVisualizerNode, SaiyanNode, SunglassesNode) from .helper_nodes import ModelResultBindingNode, MonitorNode, RecorderNode from",
"'SunglassesNode', 'ModelResultBindingNode', 'NoticeBoardNode', 'RecorderNode', 'FaceSwapNode', 'MoustacheNode', 'SaiyanNode', 'BackgroundNode', 'XDwenDwenNode' ]",
".mmdet_nodes import DetectorNode from .mmpose_nodes import TopDownPoseEstimatorNode from .xdwendwen_nodes import",
"import TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__ = [ 'NODES',",
".faceswap_nodes import FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode, MoustacheNode, NoticeBoardNode,",
"import NODES from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes import (BackgroundNode,",
"NODES from .faceswap_nodes import FaceSwapNode from .frame_effect_nodes import (BackgroundNode, BugEyeNode,",
"TopDownPoseEstimatorNode from .xdwendwen_nodes import XDwenDwenNode __all__ = [ 'NODES', 'PoseVisualizerNode',"
] |
[
"= (db, host, port, user, pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s;",
"export_file.write(\"export to %s.ixf of ixf lobs to . modified by",
"\"-h\": host = a if o == \"-P\": port =",
"== \"-h\": host = a if o == \"-P\": port",
"identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file =",
"load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column",
"host = \"localhost\" port = \"50000\" user = None pwd",
"drop generated alter column NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME",
"\"identityoverride\" if t in identity_skip_arr: identityskip = \" \" load_file.write(\"load",
"like 'SYS%' AND t.type = 'T' AND rtrim(t.tabschema) not like",
"identityskip = \"identityoverride\" if t in identity_skip_arr: identityskip = \"",
"if o == \"-h\": host = a if o ==",
"import ibm_db import getopt import sys import os from toposort",
"as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column NORMALIZED_LASTNAME set",
"tpl = ibm_db.fetch_tuple(stmt) while tpl: n1, n2 = tpl try:",
"db_type = tpl[0] edges = dict() stmt = ibm_db.prepare(conn, find_edges)",
"1 \"\"\" identity_skip = \"\"\" select rtrim(tabschema) || '.' ||",
"LEFT JOIN syscat.references r ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname)",
"exist_ok=True) export_file = open(\"%s/export.sql\" % db, \"w\") load_file = open(\"%s/load.sql\"",
"\"w\") load_file = open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect to %s;\\n\"",
"t.tabschema not like 'SYS%' AND t.type = 'T' AND rtrim(t.tabschema)",
"set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes)",
"in sorted_nodes: if t == \"dummy\": continue export_file.write(\"export to %s.ixf",
"= open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect to %s;\\n\" % db)",
"find_edges = \"\"\" SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname) ,",
"(t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema not like 'SYS%'",
"integrity for nya.person immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity",
"r ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema not",
"and generated = 'D' \"\"\" stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt,",
"load_file.write(\"load from %s.ixf of ixf lobs from . modified by",
"None or user is None or pwd is None or",
"user = None pwd = None outfile = None targetdb",
"outfile = None targetdb = None try: opts, args =",
"= 'D' \"\"\" stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl",
"-p <pwd> -t <target>\") sys.exit(1) db = db.upper() targetdb =",
"t.tabschema <> 'TMP' ORDER BY 1 \"\"\" identity_skip = \"\"\"",
"nya.get_db_type()\" find_edges = \"\"\" SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname)",
"HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg, \"\", \"\") get_db_type",
"'NYA_%' AND t.tabschema <> 'TMP' ORDER BY 1 \"\"\" identity_skip",
"= open(\"%s/export.sql\" % db, \"w\") load_file = open(\"%s/load.sql\" % db,",
"n1, n2 = tpl try: edges[n1].add(n2) except KeyError: edges[n1] =",
"== \"-p\": pwd = a if o == \"-t\": targetdb",
"\"\", \"\") get_db_type = \"values nya.get_db_type()\" find_edges = \"\"\" SELECT",
"nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC set generated",
"tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file",
"db, \"w\") export_file.write(\"connect to %s;\\n\" % db) load_file.write(\"connect to %s;\\n\"",
"SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.'",
"(r.tabschema, r.tabname) WHERE t.tabschema not like 'SYS%' AND t.type =",
"db = a if o == \"-h\": host = a",
"<gh_stars>1-10 #!/usr/bin/python3 import ibm_db import getopt import sys import os",
"None or pwd is None or targetdb is None: print(\"Usage:",
"generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked;\\n\"\"\") for t in",
"ixf lobs to . modified by codepage=819 messages export_%s.msg select",
") ) alter column NORMALIZED_LASTNAME set generated always as (",
"db is None or user is None or pwd is",
"coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT",
"export_file = open(\"%s/export.sql\" % db, \"w\") load_file = open(\"%s/load.sql\" %",
"AND t.tabschema <> 'TMP' ORDER BY 1 \"\"\" identity_skip =",
"= a if o == \"-u\": user = a if",
"== \"-t\": targetdb = a if db is None or",
"o == \"-u\": user = a if o == \"-p\":",
"= dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl =",
"immediate checked;\\n\"\"\") for t in sorted_nodes: if t == \"dummy\":",
"or targetdb is None: print(\"Usage: DBMove.py [-h <host> -P <port>]",
"None pwd = None outfile = None targetdb = None",
"cfg, \"\", \"\") get_db_type = \"values nya.get_db_type()\" find_edges = \"\"\"",
"= ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = []",
"messages export_%s.msg select * from %s;\\n\" % (t,t,t)) identityskip =",
"generated always as ( upper(email)) alter column NORMALIZED_FIRSTNAME set generated",
"ibm_db.fetch_tuple(stmt) while tpl: n1, n2 = tpl try: edges[n1].add(n2) except",
"\"-P\": port = a if o == \"-u\": user =",
". modified by codepage=819 messages export_%s.msg select * from %s;\\n\"",
"except KeyError: edges[n1] = set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes",
"load_file.write(\"\"\"set integrity for nya.person immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set",
"checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for all tables;\\n\"\"\") export_file.write(\"connect",
"= targetdb.upper() cfg = (db, host, port, user, pwd) conn",
"port = \"50000\" user = None pwd = None outfile",
"# print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\" % db, \"w\")",
"stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while",
"drop generated alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for",
"upper(email)) alter column NORMALIZED_FIRSTNAME set generated always as ( NYA.REMOVE_DIACRITICS(",
"= ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip)",
"sorted_nodes: if t == \"dummy\": continue export_file.write(\"export to %s.ixf of",
"force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for all tables;\\n\"\"\") export_file.write(\"connect reset;\\n\")",
"= ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges = dict() stmt =",
"o == \"-d\": db = a if o == \"-h\":",
"where identity = 'Y' and generated = 'D' \"\"\" stmt",
"\"w\") export_file.write(\"connect to %s;\\n\" % db) load_file.write(\"connect to %s;\\n\" %",
"alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate",
"identityskip, t, t)) if db_type == \"N\": load_file.write(\"\"\"set integrity for",
"is None or targetdb is None: print(\"Usage: DBMove.py [-h <host>",
"* from %s;\\n\" % (t,t,t)) identityskip = \"identityoverride\" if t",
"load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC drop generated alter column",
"conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg,",
"tpl[0] edges = dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ())",
"<user> -p <pwd> -t <target>\") sys.exit(1) db = db.upper() targetdb",
"% cfg, \"\", \"\") get_db_type = \"values nya.get_db_type()\" find_edges =",
"user = a if o == \"-p\": pwd = a",
"column EMAIL_UC set generated always as ( upper(email)) alter column",
"'dummy') FROM syscat.tables t LEFT JOIN syscat.references r ON (t.tabschema,",
"nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC drop generated",
"|| rtrim(tabname) from syscat.columns where identity = 'Y' and generated",
"None try: opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1)",
"a in opts: if o == \"-d\": db = a",
"opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for o,",
"t.type = 'T' AND rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema",
"ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: n1,",
"= None pwd = None outfile = None targetdb =",
"for nya.person immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for",
"print(sorted_nodes) identity_skip_arr = [] edges = dict() stmt = ibm_db.prepare(conn,",
"<host> -P <port>] -d <db> -u <user> -p <pwd> -t",
"<> 'TMP' ORDER BY 1 \"\"\" identity_skip = \"\"\" select",
"sys.exit(1) db = db.upper() targetdb = targetdb.upper() cfg = (db,",
"targetdb) if db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\")",
"[-h <host> -P <port>] -d <db> -u <user> -p <pwd>",
"select * from %s;\\n\" % (t,t,t)) identityskip = \"identityoverride\" if",
"'.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy')",
"= \"50000\" user = None pwd = None outfile =",
"or pwd is None or targetdb is None: print(\"Usage: DBMove.py",
"if t == \"dummy\": continue export_file.write(\"export to %s.ixf of ixf",
"ibm_db import getopt import sys import os from toposort import",
"FIRSTNAME ) ) alter column NORMALIZED_LASTNAME set generated always as",
"ixf lobs from . modified by generatedoverride %s messages load_%s.msg",
"toposort import toposort_flatten db = None host = \"localhost\" port",
"ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema not like",
"= getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for o, a in",
"= None try: opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError:",
"%s.ixf of ixf lobs to . modified by codepage=819 messages",
"while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True)",
"t == \"dummy\": continue export_file.write(\"export to %s.ixf of ixf lobs",
"()) tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges = dict()",
"NORMALIZED_LASTNAME set generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\")",
"identityskip = \" \" load_file.write(\"load from %s.ixf of ixf lobs",
"o == \"-p\": pwd = a if o == \"-t\":",
"\"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter",
"ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg, \"\", \"\")",
"to . modified by codepage=819 messages export_%s.msg select * from",
"syscat.references r ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema",
"targetdb is None: print(\"Usage: DBMove.py [-h <host> -P <port>] -d",
"tpl: n1, n2 = tpl try: edges[n1].add(n2) except KeyError: edges[n1]",
"for t in sorted_nodes: if t == \"dummy\": continue export_file.write(\"export",
"t)) if db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\")",
"load_%s.msg replace into %s;\\n\" % (t, identityskip, t, t)) if",
"rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT JOIN syscat.references r ON",
"(t, identityskip, t, t)) if db_type == \"N\": load_file.write(\"\"\"set integrity",
"BY 1 \"\"\" identity_skip = \"\"\" select rtrim(tabschema) || '.'",
"a if o == \"-p\": pwd = a if o",
"o == \"-t\": targetdb = a if db is None",
"LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked force",
"== \"-u\": user = a if o == \"-p\": pwd",
"identity_skip_arr: identityskip = \" \" load_file.write(\"load from %s.ixf of ixf",
"a if o == \"-t\": targetdb = a if db",
"'.' || rtrim(tabname) from syscat.columns where identity = 'Y' and",
"a if o == \"-u\": user = a if o",
"edges[n1] = set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges))",
"checked;\\n\"\"\") for t in sorted_nodes: if t == \"dummy\": continue",
"= None targetdb = None try: opts, args = getopt.getopt(sys.argv[1:],",
"getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for o, a in opts:",
"% (t,t,t)) identityskip = \"identityoverride\" if t in identity_skip_arr: identityskip",
"getopt.GetoptError: sys.exit(-1) for o, a in opts: if o ==",
"= a if db is None or user is None",
"EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME drop generated alter column",
", coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables t",
"= ibm_db.fetch_tuple(stmt) while tpl: n1, n2 = tpl try: edges[n1].add(n2)",
"KeyError: edges[n1] = set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes =",
"'D' \"\"\" stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl =",
"sys.exit(-1) for o, a in opts: if o == \"-d\":",
"targetdb = a if db is None or user is",
") alter column NORMALIZED_LASTNAME set generated always as ( NYA.REMOVE_DIACRITICS(",
"\"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for o, a in opts: if",
"while tpl: n1, n2 = tpl try: edges[n1].add(n2) except KeyError:",
"== \"dummy\": continue export_file.write(\"export to %s.ixf of ixf lobs to",
"dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt)",
"ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\" % db,",
"% db) load_file.write(\"connect to %s;\\n\" % targetdb) if db_type ==",
"= set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) #",
"from syscat.columns where identity = 'Y' and generated = 'D'",
"load_file.write(\"\"\"set integrity for nya.person immediate checked;\\n\"\"\") for t in sorted_nodes:",
"load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC set generated always as",
"find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: n1, n2",
"by codepage=819 messages export_%s.msg select * from %s;\\n\" % (t,t,t))",
"None targetdb = None try: opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\")",
"generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity",
"= a if o == \"-t\": targetdb = a if",
"|| '.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT JOIN",
"tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges = dict() stmt",
"in identity_skip_arr: identityskip = \" \" load_file.write(\"load from %s.ixf of",
"= dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl =",
"UID=%s; PWD=%s\" % cfg, \"\", \"\") get_db_type = \"values nya.get_db_type()\"",
"a if o == \"-P\": port = a if o",
"user, pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\"",
"set generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter",
"args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for o, a",
"= \" \" load_file.write(\"load from %s.ixf of ixf lobs from",
"is None or user is None or pwd is None",
"()) tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt)",
"from toposort import toposort_flatten db = None host = \"localhost\"",
"\"-p\": pwd = a if o == \"-t\": targetdb =",
"alter column NORMALIZED_FIRSTNAME set generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME",
"%s;\\n\" % (t, identityskip, t, t)) if db_type == \"N\":",
"off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC set generated always",
"WHERE t.tabschema not like 'SYS%' AND t.type = 'T' AND",
"== \"-d\": db = a if o == \"-h\": host",
"edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr",
"(db, host, port, user, pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s;",
"of ixf lobs from . modified by generatedoverride %s messages",
"-P <port>] -d <db> -u <user> -p <pwd> -t <target>\")",
"to %s;\\n\" % targetdb) if db_type == \"N\": load_file.write(\"\"\"set integrity",
"= [] edges = dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt,",
"AND t.type = 'T' AND rtrim(t.tabschema) not like 'NYA_%' AND",
"\"\") get_db_type = \"values nya.get_db_type()\" find_edges = \"\"\" SELECT rtrim(t.tabschema)",
"to %s;\\n\" % db) load_file.write(\"connect to %s;\\n\" % targetdb) if",
"not like 'SYS%' AND t.type = 'T' AND rtrim(t.tabschema) not",
"print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\" % db, \"w\") load_file",
"port, user, pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s;",
"if o == \"-u\": user = a if o ==",
"if o == \"-d\": db = a if o ==",
"os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\" % db, \"w\") load_file =",
"r.tabname) WHERE t.tabschema not like 'SYS%' AND t.type = 'T'",
"NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked",
"FROM syscat.tables t LEFT JOIN syscat.references r ON (t.tabschema, t.tabname)",
"os from toposort import toposort_flatten db = None host =",
"continue export_file.write(\"export to %s.ixf of ixf lobs to . modified",
"except getopt.GetoptError: sys.exit(-1) for o, a in opts: if o",
"immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for all tables;\\n\"\"\")",
"alter column EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME drop generated",
"( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column NORMALIZED_LASTNAME set generated",
"|| '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname),",
"sys import os from toposort import toposort_flatten db = None",
"= (r.tabschema, r.tabname) WHERE t.tabschema not like 'SYS%' AND t.type",
"None: print(\"Usage: DBMove.py [-h <host> -P <port>] -d <db> -u",
"= ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl:",
"o, a in opts: if o == \"-d\": db =",
"\"dummy\": continue export_file.write(\"export to %s.ixf of ixf lobs to .",
"generated = 'D' \"\"\" stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ())",
"generated alter column NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME drop",
"codepage=819 messages export_%s.msg select * from %s;\\n\" % (t,t,t)) identityskip",
"'T' AND rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema <> 'TMP'",
"= None outfile = None targetdb = None try: opts,",
"db, \"w\") load_file = open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect to",
"as ( upper(email)) alter column NORMALIZED_FIRSTNAME set generated always as",
"import getopt import sys import os from toposort import toposort_flatten",
"-u <user> -p <pwd> -t <target>\") sys.exit(1) db = db.upper()",
"is None: print(\"Usage: DBMove.py [-h <host> -P <port>] -d <db>",
"if db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter",
"import os from toposort import toposort_flatten db = None host",
"import sys import os from toposort import toposort_flatten db =",
"= a if o == \"-h\": host = a if",
"o == \"-h\": host = a if o == \"-P\":",
"identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl",
"tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\"",
"set integrity for all tables;\\n\"\"\") export_file.write(\"connect reset;\\n\") load_file.write(\"connect reset;\\n\") export_file.close()",
"= a if o == \"-p\": pwd = a if",
"print(\"Usage: DBMove.py [-h <host> -P <port>] -d <db> -u <user>",
"by generatedoverride %s messages load_%s.msg replace into %s;\\n\" % (t,",
"None host = \"localhost\" port = \"50000\" user = None",
"a if o == \"-h\": host = a if o",
"o == \"-P\": port = a if o == \"-u\":",
"getopt import sys import os from toposort import toposort_flatten db",
"%s;\\n\" % targetdb) if db_type == \"N\": load_file.write(\"\"\"set integrity for",
"t, t)) if db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person",
"generatedoverride %s messages load_%s.msg replace into %s;\\n\" % (t, identityskip,",
"alter column EMAIL_UC set generated always as ( upper(email)) alter",
"for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC set",
"from %s.ixf of ixf lobs from . modified by generatedoverride",
"for o, a in opts: if o == \"-d\": db",
"\" \" load_file.write(\"load from %s.ixf of ixf lobs from .",
"integrity for all tables;\\n\"\"\") export_file.write(\"connect reset;\\n\") load_file.write(\"connect reset;\\n\") export_file.close() load_file.close()",
"as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person",
"set generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set",
"opts: if o == \"-d\": db = a if o",
"= a if o == \"-P\": port = a if",
"<pwd> -t <target>\") sys.exit(1) db = db.upper() targetdb = targetdb.upper()",
"PWD=%s\" % cfg, \"\", \"\") get_db_type = \"values nya.get_db_type()\" find_edges",
"targetdb = targetdb.upper() cfg = (db, host, port, user, pwd)",
"from . modified by generatedoverride %s messages load_%s.msg replace into",
"generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for all tables;\\n\"\"\") export_file.write(\"connect reset;\\n\") load_file.write(\"connect",
"|| rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy') FROM",
"open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect to %s;\\n\" % db) load_file.write(\"connect",
"column EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME drop generated alter",
"db.upper() targetdb = targetdb.upper() cfg = (db, host, port, user,",
"load_file = open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect to %s;\\n\" %",
"tpl = ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr =",
"port = a if o == \"-u\": user = a",
"<target>\") sys.exit(1) db = db.upper() targetdb = targetdb.upper() cfg =",
"ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db,",
"t in sorted_nodes: if t == \"dummy\": continue export_file.write(\"export to",
"-t <target>\") sys.exit(1) db = db.upper() targetdb = targetdb.upper() cfg",
"\"\"\" SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) ||",
"alter column NORMALIZED_LASTNAME set generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME",
"sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = [] edges =",
"pwd = a if o == \"-t\": targetdb = a",
". modified by generatedoverride %s messages load_%s.msg replace into %s;\\n\"",
"try: edges[n1].add(n2) except KeyError: edges[n1] = set() edges[n1].add(n2) tpl =",
"for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC drop",
"off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC drop generated alter",
"rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables",
"nya.person immediate checked;\\n\"\"\") for t in sorted_nodes: if t ==",
"export_%s.msg select * from %s;\\n\" % (t,t,t)) identityskip = \"identityoverride\"",
"%s messages load_%s.msg replace into %s;\\n\" % (t, identityskip, t,",
"-d <db> -u <user> -p <pwd> -t <target>\") sys.exit(1) db",
"= \"\"\" SELECT rtrim(t.tabschema) || '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema)",
"= list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = [] edges = dict()",
"modified by codepage=819 messages export_%s.msg select * from %s;\\n\" %",
"of ixf lobs to . modified by codepage=819 messages export_%s.msg",
"[] edges = dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ())",
"( upper(email)) alter column NORMALIZED_FIRSTNAME set generated always as (",
"% db, \"w\") export_file.write(\"connect to %s;\\n\" % db) load_file.write(\"connect to",
"select rtrim(tabschema) || '.' || rtrim(tabname) from syscat.columns where identity",
"PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg, \"\", \"\") get_db_type =",
"= 'T' AND rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema <>",
"'Y' and generated = 'D' \"\"\" stmt = ibm_db.prepare(conn, get_db_type)",
"targetdb.upper() cfg = (db, host, port, user, pwd) conn =",
"\"values nya.get_db_type()\" find_edges = \"\"\" SELECT rtrim(t.tabschema) || '.' ||",
"t in identity_skip_arr: identityskip = \" \" load_file.write(\"load from %s.ixf",
");\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo",
"db = db.upper() targetdb = targetdb.upper() cfg = (db, host,",
"into %s;\\n\" % (t, identityskip, t, t)) if db_type ==",
"for nya.person immediate checked;\\n\"\"\") for t in sorted_nodes: if t",
"'.' || rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT JOIN syscat.references",
"table nya.person alter column EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME",
"%s;\\n\" % (t,t,t)) identityskip = \"identityoverride\" if t in identity_skip_arr:",
"|| '.' || rtrim(tabname) from syscat.columns where identity = 'Y'",
"generated alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person",
"|| rtrim(r.reftabname), 'dummy') FROM syscat.tables t LEFT JOIN syscat.references r",
"if db is None or user is None or pwd",
"edges[n1].add(n2) except KeyError: edges[n1] = set() edges[n1].add(n2) tpl = ibm_db.fetch_tuple(stmt)",
"%s.ixf of ixf lobs from . modified by generatedoverride %s",
"ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges =",
"to %s.ixf of ixf lobs to . modified by codepage=819",
"= \"values nya.get_db_type()\" find_edges = \"\"\" SELECT rtrim(t.tabschema) || '.'",
"DBMove.py [-h <host> -P <port>] -d <db> -u <user> -p",
"try: opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except getopt.GetoptError: sys.exit(-1) for",
"always as ( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity for",
"column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked;\\n\"\"\")",
"integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person alter column EMAIL_UC",
"= ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type =",
"if o == \"-p\": pwd = a if o ==",
"identity_skip = \"\"\" select rtrim(tabschema) || '.' || rtrim(tabname) from",
"None outfile = None targetdb = None try: opts, args",
"rtrim(tabname) from syscat.columns where identity = 'Y' and generated =",
"load_file.write(\"\"\"echo set integrity for all tables;\\n\"\"\") export_file.write(\"connect reset;\\n\") load_file.write(\"connect reset;\\n\")",
"\"\"\" identity_skip = \"\"\" select rtrim(tabschema) || '.' || rtrim(tabname)",
"\"\"\" select rtrim(tabschema) || '.' || rtrim(tabname) from syscat.columns where",
"like 'NYA_%' AND t.tabschema <> 'TMP' ORDER BY 1 \"\"\"",
"syscat.tables t LEFT JOIN syscat.references r ON (t.tabschema, t.tabname) =",
"NORMALIZED_FIRSTNAME set generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) )",
"or user is None or pwd is None or targetdb",
"ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0]",
"= tpl[0] edges = dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt,",
"= tpl try: edges[n1].add(n2) except KeyError: edges[n1] = set() edges[n1].add(n2)",
"\"localhost\" port = \"50000\" user = None pwd = None",
"drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked;\\n\"\"\") for t",
"cfg = (db, host, port, user, pwd) conn = ibm_db.connect(\"DATABASE=%s;",
"ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0])",
"JOIN syscat.references r ON (t.tabschema, t.tabname) = (r.tabschema, r.tabname) WHERE",
"rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema <> 'TMP' ORDER BY",
"% db, \"w\") load_file = open(\"%s/load.sql\" % db, \"w\") export_file.write(\"connect",
"edges = dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl",
"= \"\"\" select rtrim(tabschema) || '.' || rtrim(tabname) from syscat.columns",
"= 'Y' and generated = 'D' \"\"\" stmt = ibm_db.prepare(conn,",
"\"-u\": user = a if o == \"-p\": pwd =",
"== \"-P\": port = a if o == \"-u\": user",
"ibm_db.fetch_tuple(stmt) sorted_nodes = list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = [] edges",
"alter column NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\")",
"integrity for nya.person immediate checked;\\n\"\"\") for t in sorted_nodes: if",
"not like 'NYA_%' AND t.tabschema <> 'TMP' ORDER BY 1",
"( NYA.REMOVE_DIACRITICS( LASTNAME ) );\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate",
"rtrim(t.tabschema) || '.' || rtrim(t.tabname) , coalesce(rtrim(r.reftabschema) || '.' ||",
"get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges",
"import toposort_flatten db = None host = \"localhost\" port =",
"is None or pwd is None or targetdb is None:",
"pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" %",
"in opts: if o == \"-d\": db = a if",
"tpl try: edges[n1].add(n2) except KeyError: edges[n1] = set() edges[n1].add(n2) tpl",
"table nya.person alter column EMAIL_UC set generated always as (",
"= \"localhost\" port = \"50000\" user = None pwd =",
"pwd is None or targetdb is None: print(\"Usage: DBMove.py [-h",
"edges = dict() stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl",
"nya.person alter column EMAIL_UC set generated always as ( upper(email))",
"list(toposort_flatten(edges)) # print(sorted_nodes) identity_skip_arr = [] edges = dict() stmt",
"a if db is None or user is None or",
"if t in identity_skip_arr: identityskip = \" \" load_file.write(\"load from",
"tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl = ibm_db.fetch_tuple(stmt) #",
"load_file.write(\"connect to %s;\\n\" % targetdb) if db_type == \"N\": load_file.write(\"\"\"set",
"t LEFT JOIN syscat.references r ON (t.tabschema, t.tabname) = (r.tabschema,",
"= db.upper() targetdb = targetdb.upper() cfg = (db, host, port,",
"\"-d\": db = a if o == \"-h\": host =",
"always as ( upper(email)) alter column NORMALIZED_FIRSTNAME set generated always",
"user is None or pwd is None or targetdb is",
"ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: n1, n2 =",
"== \"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table nya.person",
"if o == \"-P\": port = a if o ==",
"from %s;\\n\" % (t,t,t)) identityskip = \"identityoverride\" if t in",
"pwd = None outfile = None targetdb = None try:",
"= ibm_db.fetch_tuple(stmt) # print(identity_skip) os.makedirs(db, exist_ok=True) export_file = open(\"%s/export.sql\" %",
"open(\"%s/export.sql\" % db, \"w\") load_file = open(\"%s/load.sql\" % db, \"w\")",
"\"-t\": targetdb = a if db is None or user",
"% (t, identityskip, t, t)) if db_type == \"N\": load_file.write(\"\"\"set",
"identity_skip_arr = [] edges = dict() stmt = ibm_db.prepare(conn, identity_skip)",
"NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked;\\n\"\"\") for",
"modified by generatedoverride %s messages load_%s.msg replace into %s;\\n\" %",
"NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column NORMALIZED_LASTNAME set generated always",
"syscat.columns where identity = 'Y' and generated = 'D' \"\"\"",
"%s;\\n\" % db) load_file.write(\"connect to %s;\\n\" % targetdb) if db_type",
"nya.person immediate checked force generated;\\n\"\"\") load_file.write(\"\"\"echo set integrity for all",
"ibm_db.fetch_tuple(stmt) db_type = tpl[0] edges = dict() stmt = ibm_db.prepare(conn,",
"toposort_flatten db = None host = \"localhost\" port = \"50000\"",
"set generated always as ( upper(email)) alter column NORMALIZED_FIRSTNAME set",
"= ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg, \"\",",
"column NORMALIZED_FIRSTNAME set generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME )",
"db = None host = \"localhost\" port = \"50000\" user",
"= ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl:",
"ORDER BY 1 \"\"\" identity_skip = \"\"\" select rtrim(tabschema) ||",
"'TMP' ORDER BY 1 \"\"\" identity_skip = \"\"\" select rtrim(tabschema)",
"host, port, user, pwd) conn = ibm_db.connect(\"DATABASE=%s; HOSTNAME=%s; PORT=%s; PROTOCOL=TCPIP;",
"<port>] -d <db> -u <user> -p <pwd> -t <target>\") sys.exit(1)",
"column NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set",
"rtrim(tabschema) || '.' || rtrim(tabname) from syscat.columns where identity =",
"None or targetdb is None: print(\"Usage: DBMove.py [-h <host> -P",
"= \"identityoverride\" if t in identity_skip_arr: identityskip = \" \"",
"t.tabname) = (r.tabschema, r.tabname) WHERE t.tabschema not like 'SYS%' AND",
"identity = 'Y' and generated = 'D' \"\"\" stmt =",
"targetdb = None try: opts, args = getopt.getopt(sys.argv[1:], \"h:d:P:u:p:o:t:\") except",
"\"50000\" user = None pwd = None outfile = None",
"n2 = tpl try: edges[n1].add(n2) except KeyError: edges[n1] = set()",
"column NORMALIZED_LASTNAME set generated always as ( NYA.REMOVE_DIACRITICS( LASTNAME )",
"get_db_type = \"values nya.get_db_type()\" find_edges = \"\"\" SELECT rtrim(t.tabschema) ||",
") );\\n\"\"\") load_file.write(\"\"\"set integrity for nya.person immediate checked force generated;\\n\"\"\")",
"<db> -u <user> -p <pwd> -t <target>\") sys.exit(1) db =",
"()) tpl = ibm_db.fetch_tuple(stmt) while tpl: n1, n2 = tpl",
"= None host = \"localhost\" port = \"50000\" user =",
"# print(sorted_nodes) identity_skip_arr = [] edges = dict() stmt =",
"\"\"\" stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt)",
"db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person off;\\n\"\"\") load_file.write(\"\"\"alter table",
"(t,t,t)) identityskip = \"identityoverride\" if t in identity_skip_arr: identityskip =",
"EMAIL_UC set generated always as ( upper(email)) alter column NORMALIZED_FIRSTNAME",
"replace into %s;\\n\" % (t, identityskip, t, t)) if db_type",
"if o == \"-t\": targetdb = a if db is",
"AND rtrim(t.tabschema) not like 'NYA_%' AND t.tabschema <> 'TMP' ORDER",
"export_file.write(\"connect to %s;\\n\" % db) load_file.write(\"connect to %s;\\n\" % targetdb)",
"dict() stmt = ibm_db.prepare(conn, find_edges) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt)",
"stmt = ibm_db.prepare(conn, identity_skip) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while",
"stmt = ibm_db.prepare(conn, get_db_type) ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) db_type",
"nya.person alter column EMAIL_UC drop generated alter column NORMALIZED_FIRSTNAME drop",
"generated always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column",
"lobs to . modified by codepage=819 messages export_%s.msg select *",
"messages load_%s.msg replace into %s;\\n\" % (t, identityskip, t, t))",
"\" load_file.write(\"load from %s.ixf of ixf lobs from . modified",
"'SYS%' AND t.type = 'T' AND rtrim(t.tabschema) not like 'NYA_%'",
"% targetdb) if db_type == \"N\": load_file.write(\"\"\"set integrity for nya.person",
"lobs from . modified by generatedoverride %s messages load_%s.msg replace",
"db) load_file.write(\"connect to %s;\\n\" % targetdb) if db_type == \"N\":",
"host = a if o == \"-P\": port = a",
"NORMALIZED_FIRSTNAME drop generated alter column NORMALIZED_LASTNAME drop generated;\\n\"\"\") load_file.write(\"\"\"set integrity",
"ibm_db.execute(stmt, ()) tpl = ibm_db.fetch_tuple(stmt) while tpl: identity_skip_arr.append(tpl[0]) tpl =",
"#!/usr/bin/python3 import ibm_db import getopt import sys import os from",
"PROTOCOL=TCPIP; UID=%s; PWD=%s\" % cfg, \"\", \"\") get_db_type = \"values",
"always as ( NYA.REMOVE_DIACRITICS( FIRSTNAME ) ) alter column NORMALIZED_LASTNAME"
] |
[
"data = [float(x) for x in row[1:]] if len(data) !=",
"open(filepath) as ifs: for line in ifs: line = line.strip()",
"for x in row[1:]] if len(data) != dimensions: raise RuntimeError(\"wrong",
"for line in ifs: line = line.strip() if not line:",
"import numpy as np DEFAULT_FILE_PATH = \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH,",
"dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions)) with",
"line: continue row = line.split() token = row[0] if token",
"continue row = line.split() token = row[0] if token not",
"= line.split() token = row[0] if token not in tokens:",
"in ifs: line = line.strip() if not line: continue row",
"pretrained GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as",
"line in ifs: line = line.strip() if not line: continue",
"= \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\"",
"line.split() token = row[0] if token not in tokens: continue",
"tokens: continue data = [float(x) for x in row[1:]] if",
"row[1:]] if len(data) != dimensions: raise RuntimeError(\"wrong number of dimensions\")",
"\"\"\"Read pretrained GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath)",
"row = line.split() token = row[0] if token not in",
"as np DEFAULT_FILE_PATH = \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read",
"as ifs: for line in ifs: line = line.strip() if",
"line = line.strip() if not line: continue row = line.split()",
"continue data = [float(x) for x in row[1:]] if len(data)",
"!= dimensions: raise RuntimeError(\"wrong number of dimensions\") wordVectors[tokens[token]] = np.asarray(data)",
"numpy as np DEFAULT_FILE_PATH = \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50):",
"np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for line in ifs:",
"not line: continue row = line.split() token = row[0] if",
"token not in tokens: continue data = [float(x) for x",
"with open(filepath) as ifs: for line in ifs: line =",
"in row[1:]] if len(data) != dimensions: raise RuntimeError(\"wrong number of",
"dimensions)) with open(filepath) as ifs: for line in ifs: line",
"filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions))",
"def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\" wordVectors =",
"dimensions: raise RuntimeError(\"wrong number of dimensions\") wordVectors[tokens[token]] = np.asarray(data) return",
"raise RuntimeError(\"wrong number of dimensions\") wordVectors[tokens[token]] = np.asarray(data) return wordVectors",
"vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for",
"\"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\" wordVectors",
"wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for line",
"in tokens: continue data = [float(x) for x in row[1:]]",
"len(data) != dimensions: raise RuntimeError(\"wrong number of dimensions\") wordVectors[tokens[token]] =",
"row[0] if token not in tokens: continue data = [float(x)",
"np DEFAULT_FILE_PATH = \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained",
"GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens), dimensions)) with open(filepath) as ifs:",
"= np.zeros((len(tokens), dimensions)) with open(filepath) as ifs: for line in",
"= line.strip() if not line: continue row = line.split() token",
"[float(x) for x in row[1:]] if len(data) != dimensions: raise",
"= row[0] if token not in tokens: continue data =",
"line.strip() if not line: continue row = line.split() token =",
"if len(data) != dimensions: raise RuntimeError(\"wrong number of dimensions\") wordVectors[tokens[token]]",
"ifs: for line in ifs: line = line.strip() if not",
"ifs: line = line.strip() if not line: continue row =",
"if not line: continue row = line.split() token = row[0]",
"token = row[0] if token not in tokens: continue data",
"if token not in tokens: continue data = [float(x) for",
"loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe vectors\"\"\" wordVectors = np.zeros((len(tokens),",
"DEFAULT_FILE_PATH = \"utils/datasets/glove.6B.50d.txt\" def loadWordVectors(tokens, filepath=DEFAULT_FILE_PATH, dimensions=50): \"\"\"Read pretrained GloVe",
"not in tokens: continue data = [float(x) for x in",
"= [float(x) for x in row[1:]] if len(data) != dimensions:",
"x in row[1:]] if len(data) != dimensions: raise RuntimeError(\"wrong number"
] |
[
"and facilitate model development. The metrics gathered include: * Duration",
"GPU kernels (see :doc:`profiler`) The following example demonstrates how to",
"profiler gathers performance metrics during a training run that can",
"to return a batch * Host metrics such as CPU,",
"the Torch Profiler traces once the profiling run completes. The",
"Duration of each :class:`.Event` during training * Time taken by",
".. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File :align: center",
"Marker.__module__ = __name__ Profiler.__module__ = __name__ ProfilerAction.__module__ = __name__ ProfilerEventHandler.__module__",
"gathered include: * Duration of each :class:`.Event` during training *",
"that can be used to diagnose bottlenecks and facilitate model",
"Torch traces in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users",
"found in the Profiler Guide. \"\"\" from composer.profiler._event_handler import ProfilerEventHandler",
"over time * Execution order, latency and attributes of PyTorch",
"python :linenos: :emphasize-lines: 6, 27-49 It is required to specify",
"contain the profiling trace data once the profiling run completes.",
"in the Profiler Guide. \"\"\" from composer.profiler._event_handler import ProfilerEventHandler from",
"by the data loader to return a batch * Host",
"utilization over time * Execution order, latency and attributes of",
"* Execution order, latency and attributes of PyTorch operators and",
"Copyright 2021 MosaicML. All Rights Reserved. \"\"\"Performance profiling tools. The",
"The metrics gathered include: * Duration of each :class:`.Event` during",
"``profiler_trace_file`` will contain the profiling trace data once the profiling",
"an output ``profiler_trace_file`` during :class:`.Trainer` initialization to enable profiling. The",
"be active. The :class:`.TorchProfiler` is **disabled** by default. To activate",
"to diagnose bottlenecks and facilitate model development. The metrics gathered",
"include: * Duration of each :class:`.Event` during training * Time",
"PyTorch operators and GPU kernels (see :doc:`profiler`) The following example",
"merge the Torch traces in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``,",
"by in a Google Chrome browser navigating to ``chrome://tracing`` and",
"file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File :align:",
"be found in the Profiler Guide. \"\"\" from composer.profiler._event_handler import",
"All Rights Reserved. \"\"\"Performance profiling tools. The profiler gathers performance",
"# All needs to be defined properly for sphinx autosummary",
"contain the Torch Profiler traces once the profiling run completes.",
"All needs to be defined properly for sphinx autosummary __all__",
"MosaicML. All Rights Reserved. \"\"\"Performance profiling tools. The profiler gathers",
"CPU, system memory, disk and network utilization over time *",
"enable profiling. The ``profiler_trace_file`` will contain the profiling trace data",
"performance metrics during a training run that can be used",
"unified trace. The complete traces can be viewed by in",
"training run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6,",
"data once the profiling run completes. By default, the :class:`.Profiler`,",
"Host metrics such as CPU, system memory, disk and network",
":doc:`profiler`) The following example demonstrates how to setup and perform",
":class:`.TorchProfiler` is **disabled** by default. To activate the :class:`.TorchProfiler`, the",
"taken by the data loader to return a batch *",
":emphasize-lines: 6, 27-49 It is required to specify an output",
":class:`.Trainer` initialization to enable profiling. The ``profiler_trace_file`` will contain the",
"from composer.profiler._profiler_action import ProfilerAction # All needs to be defined",
"loading the ``profiler_trace_file``. Here is an example trace file: ..",
"File :align: center Additonal details an be found in the",
"defined properly for sphinx autosummary __all__ = [ \"Marker\", \"Profiler\",",
"[ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ = __name__ Profiler.__module__",
"https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File :align: center Additonal details",
"a Google Chrome browser navigating to ``chrome://tracing`` and loading the",
"demonstrates how to setup and perform profiling on a simple",
"\"\"\"Performance profiling tools. The profiler gathers performance metrics during a",
"The :class:`.Profiler` will automatically merge the Torch traces in the",
"be used to diagnose bottlenecks and facilitate model development. The",
"required to specify an output ``profiler_trace_file`` during :class:`.Trainer` initialization to",
"import Marker, Profiler from composer.profiler._profiler_action import ProfilerAction # All needs",
"can be used to diagnose bottlenecks and facilitate model development.",
"to enable profiling. The ``profiler_trace_file`` will contain the profiling trace",
"6, 27-49 It is required to specify an output ``profiler_trace_file``",
"the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users to view a",
"initialization to enable profiling. The ``profiler_trace_file`` will contain the profiling",
"to view a unified trace. The complete traces can be",
"training run that can be used to diagnose bottlenecks and",
"a training run that can be used to diagnose bottlenecks",
"import ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action import",
"composer.profiler._profiler_action import ProfilerAction # All needs to be defined properly",
"Here is an example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt:",
"is an example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example",
"simple training run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines:",
"By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active.",
"traces in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users to",
"properly for sphinx autosummary __all__ = [ \"Marker\", \"Profiler\", \"ProfilerAction\",",
"each :class:`.Event` during training * Time taken by the data",
"once the profiling run completes. The :class:`.Profiler` will automatically merge",
"needs to be defined properly for sphinx autosummary __all__ =",
"and loading the ``profiler_trace_file``. Here is an example trace file:",
"used to diagnose bottlenecks and facilitate model development. The metrics",
"during :class:`.Trainer` initialization to enable profiling. The ``profiler_trace_file`` will contain",
"will contain the Torch Profiler traces once the profiling run",
"of PyTorch operators and GPU kernels (see :doc:`profiler`) The following",
"The following example demonstrates how to setup and perform profiling",
"tools. The profiler gathers performance metrics during a training run",
"output ``profiler_trace_file`` during :class:`.Trainer` initialization to enable profiling. The ``profiler_trace_file``",
"gathers performance metrics during a training run that can be",
"and GPU kernels (see :doc:`profiler`) The following example demonstrates how",
"profiling tools. The profiler gathers performance metrics during a training",
":language: python :linenos: :emphasize-lines: 6, 27-49 It is required to",
"by default. To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be",
"example demonstrates how to setup and perform profiling on a",
"how to setup and perform profiling on a simple training",
"users to view a unified trace. The complete traces can",
"Additonal details an be found in the Profiler Guide. \"\"\"",
"the Profiler Guide. \"\"\" from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler",
"default. To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified",
"autosummary __all__ = [ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__",
"Time taken by the data loader to return a batch",
"on a simple training run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python",
"diagnose bottlenecks and facilitate model development. The metrics gathered include:",
"in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users to view",
"default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active. The",
"the ``profiler_trace_file``. Here is an example trace file: .. image::",
"from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler from",
"``profiler_trace_file`` during :class:`.Trainer` initialization to enable profiling. The ``profiler_trace_file`` will",
"is **disabled** by default. To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir``",
"``torch_profiler_trace_dir`` will contain the Torch Profiler traces once the profiling",
"batch * Host metrics such as CPU, system memory, disk",
"trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File",
"metrics during a training run that can be used to",
"<gh_stars>0 # Copyright 2021 MosaicML. All Rights Reserved. \"\"\"Performance profiling",
"and :class:`.SystemProfiler` will be active. The :class:`.TorchProfiler` is **disabled** by",
"run that can be used to diagnose bottlenecks and facilitate",
"the profiling run completes. The :class:`.Profiler` will automatically merge the",
"Profiler from composer.profiler._profiler_action import ProfilerAction # All needs to be",
"The ``torch_profiler_trace_dir`` will contain the Torch Profiler traces once the",
"\"\"\" from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler",
"to ``chrome://tracing`` and loading the ``profiler_trace_file``. Here is an example",
"be defined properly for sphinx autosummary __all__ = [ \"Marker\",",
"active. The :class:`.TorchProfiler` is **disabled** by default. To activate the",
"\"ProfilerEventHandler\", ] Marker.__module__ = __name__ Profiler.__module__ = __name__ ProfilerAction.__module__ =",
"a batch * Host metrics such as CPU, system memory,",
"specify an output ``profiler_trace_file`` during :class:`.Trainer` initialization to enable profiling.",
"``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain the Torch Profiler traces",
"Profiler traces once the profiling run completes. The :class:`.Profiler` will",
"run completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will",
"Rights Reserved. \"\"\"Performance profiling tools. The profiler gathers performance metrics",
"an be found in the Profiler Guide. \"\"\" from composer.profiler._event_handler",
"traces can be viewed by in a Google Chrome browser",
"To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified *in",
"navigating to ``chrome://tracing`` and loading the ``profiler_trace_file``. Here is an",
"Profiler Guide. \"\"\" from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import",
"sphinx autosummary __all__ = [ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ]",
"the profiling trace data once the profiling run completes. By",
"disk and network utilization over time * Execution order, latency",
"trace data once the profiling run completes. By default, the",
"and perform profiling on a simple training run. .. literalinclude::",
"] Marker.__module__ = __name__ Profiler.__module__ = __name__ ProfilerAction.__module__ = __name__",
"Execution order, latency and attributes of PyTorch operators and GPU",
"../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6, 27-49 It is required",
"operators and GPU kernels (see :doc:`profiler`) The following example demonstrates",
"Trace File :align: center Additonal details an be found in",
"and attributes of PyTorch operators and GPU kernels (see :doc:`profiler`)",
"view a unified trace. The complete traces can be viewed",
"setup and perform profiling on a simple training run. ..",
"the Torch traces in the ``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing",
"during training * Time taken by the data loader to",
"once the profiling run completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler`",
"the data loader to return a batch * Host metrics",
"\"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ = __name__ Profiler.__module__ = __name__",
"to setup and perform profiling on a simple training run.",
"the profiling run completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and",
"argument. The ``torch_profiler_trace_dir`` will contain the Torch Profiler traces once",
"into the ``profiler_trace_file``, allowing users to view a unified trace.",
":class:`.SystemProfiler` will be active. The :class:`.TorchProfiler` is **disabled** by default.",
"must be specified *in addition* to the ``profiler_trace_file`` argument. The",
"model development. The metrics gathered include: * Duration of each",
"metrics gathered include: * Duration of each :class:`.Event` during training",
"the ``torch_profiler_trace_dir`` must be specified *in addition* to the ``profiler_trace_file``",
"as CPU, system memory, disk and network utilization over time",
"will contain the profiling trace data once the profiling run",
"Marker, Profiler from composer.profiler._profiler_action import ProfilerAction # All needs to",
"traces once the profiling run completes. The :class:`.Profiler` will automatically",
"a unified trace. The complete traces can be viewed by",
"during a training run that can be used to diagnose",
".. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6, 27-49 It",
"automatically merge the Torch traces in the ``torch_profiler_trace_dir`` into the",
"profiling run completes. The :class:`.Profiler` will automatically merge the Torch",
"*in addition* to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain",
"addition* to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain the",
"latency and attributes of PyTorch operators and GPU kernels (see",
"profiling trace data once the profiling run completes. By default,",
"for sphinx autosummary __all__ = [ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\",",
"The ``profiler_trace_file`` will contain the profiling trace data once the",
"composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action",
"such as CPU, system memory, disk and network utilization over",
"the ``profiler_trace_file``, allowing users to view a unified trace. The",
"profiling run completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler`",
"Torch Profiler traces once the profiling run completes. The :class:`.Profiler`",
"2021 MosaicML. All Rights Reserved. \"\"\"Performance profiling tools. The profiler",
"the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active. The :class:`.TorchProfiler`",
"``torch_profiler_trace_dir`` must be specified *in addition* to the ``profiler_trace_file`` argument.",
"to specify an output ``profiler_trace_file`` during :class:`.Trainer` initialization to enable",
"training * Time taken by the data loader to return",
"profiling on a simple training run. .. literalinclude:: ../../../examples/profiler_demo.py :language:",
"run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6, 27-49",
"in a Google Chrome browser navigating to ``chrome://tracing`` and loading",
"``profiler_trace_file``. Here is an example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png",
"an example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler",
"\"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ = __name__ Profiler.__module__ = __name__ ProfilerAction.__module__",
"* Time taken by the data loader to return a",
"center Additonal details an be found in the Profiler Guide.",
"= [ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ = __name__",
"time * Execution order, latency and attributes of PyTorch operators",
"# Copyright 2021 MosaicML. All Rights Reserved. \"\"\"Performance profiling tools.",
"order, latency and attributes of PyTorch operators and GPU kernels",
"complete traces can be viewed by in a Google Chrome",
"Chrome browser navigating to ``chrome://tracing`` and loading the ``profiler_trace_file``. Here",
":linenos: :emphasize-lines: 6, 27-49 It is required to specify an",
"Profiler Trace File :align: center Additonal details an be found",
"from composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action import ProfilerAction #",
"return a batch * Host metrics such as CPU, system",
"data loader to return a batch * Host metrics such",
"details an be found in the Profiler Guide. \"\"\" from",
"is required to specify an output ``profiler_trace_file`` during :class:`.Trainer` initialization",
"It is required to specify an output ``profiler_trace_file`` during :class:`.Trainer`",
"import ProfilerAction # All needs to be defined properly for",
"__name__ Profiler.__module__ = __name__ ProfilerAction.__module__ = __name__ ProfilerEventHandler.__module__ = __name__",
"will automatically merge the Torch traces in the ``torch_profiler_trace_dir`` into",
"* Duration of each :class:`.Event` during training * Time taken",
":class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active. The :class:`.TorchProfiler` is",
"completes. The :class:`.Profiler` will automatically merge the Torch traces in",
"Google Chrome browser navigating to ``chrome://tracing`` and loading the ``profiler_trace_file``.",
"be viewed by in a Google Chrome browser navigating to",
"image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace File :align: center Additonal",
"\"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ = __name__ Profiler.__module__ =",
":align: center Additonal details an be found in the Profiler",
"attributes of PyTorch operators and GPU kernels (see :doc:`profiler`) The",
"to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain the Torch",
"of each :class:`.Event` during training * Time taken by the",
"activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified *in addition*",
":class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified *in addition* to the",
"``profiler_trace_file``, allowing users to view a unified trace. The complete",
"27-49 It is required to specify an output ``profiler_trace_file`` during",
"completes. By default, the :class:`.Profiler`, :class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be",
"ProfilerEventHandler from composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action import ProfilerAction",
":class:`.Event` during training * Time taken by the data loader",
"system memory, disk and network utilization over time * Execution",
"be specified *in addition* to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir``",
"kernels (see :doc:`profiler`) The following example demonstrates how to setup",
"profiling. The ``profiler_trace_file`` will contain the profiling trace data once",
"Example Profiler Trace File :align: center Additonal details an be",
"the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must be specified *in addition* to",
"= __name__ Profiler.__module__ = __name__ ProfilerAction.__module__ = __name__ ProfilerEventHandler.__module__ =",
"the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will contain the Torch Profiler",
"The complete traces can be viewed by in a Google",
"facilitate model development. The metrics gathered include: * Duration of",
"and network utilization over time * Execution order, latency and",
"literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos: :emphasize-lines: 6, 27-49 It is",
"__all__ = [ \"Marker\", \"Profiler\", \"ProfilerAction\", \"ProfilerEventHandler\", ] Marker.__module__ =",
":class:`.DataloaderProfiler` and :class:`.SystemProfiler` will be active. The :class:`.TorchProfiler` is **disabled**",
"can be viewed by in a Google Chrome browser navigating",
"viewed by in a Google Chrome browser navigating to ``chrome://tracing``",
"Guide. \"\"\" from composer.profiler._event_handler import ProfilerEventHandler from composer.profiler._profiler import Marker,",
"development. The metrics gathered include: * Duration of each :class:`.Event`",
"allowing users to view a unified trace. The complete traces",
"ProfilerAction # All needs to be defined properly for sphinx",
"loader to return a batch * Host metrics such as",
"Reserved. \"\"\"Performance profiling tools. The profiler gathers performance metrics during",
"composer.profiler._profiler import Marker, Profiler from composer.profiler._profiler_action import ProfilerAction # All",
"metrics such as CPU, system memory, disk and network utilization",
"following example demonstrates how to setup and perform profiling on",
"example trace file: .. image:: https://storage.googleapis.com/docs.mosaicml.com/images/profiler/profiler_trace_example.png :alt: Example Profiler Trace",
"perform profiling on a simple training run. .. literalinclude:: ../../../examples/profiler_demo.py",
"(see :doc:`profiler`) The following example demonstrates how to setup and",
"will be active. The :class:`.TorchProfiler` is **disabled** by default. To",
"specified *in addition* to the ``profiler_trace_file`` argument. The ``torch_profiler_trace_dir`` will",
"The profiler gathers performance metrics during a training run that",
"run completes. The :class:`.Profiler` will automatically merge the Torch traces",
":class:`.Profiler` will automatically merge the Torch traces in the ``torch_profiler_trace_dir``",
"memory, disk and network utilization over time * Execution order,",
"trace. The complete traces can be viewed by in a",
":alt: Example Profiler Trace File :align: center Additonal details an",
"``chrome://tracing`` and loading the ``profiler_trace_file``. Here is an example trace",
"bottlenecks and facilitate model development. The metrics gathered include: *",
"* Host metrics such as CPU, system memory, disk and",
"The :class:`.TorchProfiler` is **disabled** by default. To activate the :class:`.TorchProfiler`,",
"**disabled** by default. To activate the :class:`.TorchProfiler`, the ``torch_profiler_trace_dir`` must",
"``torch_profiler_trace_dir`` into the ``profiler_trace_file``, allowing users to view a unified",
"network utilization over time * Execution order, latency and attributes",
"to be defined properly for sphinx autosummary __all__ = [",
"a simple training run. .. literalinclude:: ../../../examples/profiler_demo.py :language: python :linenos:",
"browser navigating to ``chrome://tracing`` and loading the ``profiler_trace_file``. Here is"
] |
[
"containing the version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP',",
":: Developers\", \"License :: OSI Approved :: Apache Software License\",",
"License. ''' import codecs import os import sys import time",
"agreements. See the NOTICE file distributed with this work for",
"governing permissions and limitations under the License. ''' import codecs",
"Unless required by applicable law or agreed to in writing,",
"to the Apache Software Foundation (ASF) under one or more",
"by applicable law or agreed to in writing, software distributed",
"limitations under the License. ''' import codecs import os import",
"Path to __version__ module version_file = os.path.join(root, 'gremlin_python', '__version__.py') #",
"# Check if this is a source distribution. # If",
"os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module version_file = os.path.join(root, 'gremlin_python',",
"+= ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure',",
"software distributed under the License is distributed on an \"AS",
"distributed under the License is distributed on an \"AS IS\"",
"not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000)) /",
"'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT',",
"for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])],",
"version_file = os.path.join(root, 'gremlin_python', '__version__.py') # Check if this is",
"['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'],",
"Foundation (ASF) under one or more contributor license agreements. See",
"CONDITIONS OF ANY KIND, either express or implied. See the",
"] if sys.version_info < (3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython',",
"more contributor license agreements. See the NOTICE file distributed with",
"Version 2.0 (the \"License\"); you may not use this file",
"% timestamp) fd.close() # Load version from gremlin_python import __version__",
"Language :: Python :: 2.7\", \"Programming Language :: Python ::",
"module containing the version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp =",
"'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop',",
"license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(),",
"writing, software distributed under the License is distributed on an",
"Licensed to the Apache Software Foundation (ASF) under one or",
"this is a source distribution. # If not create the",
"the Apache Software Foundation (ASF) under one or more contributor",
"import sys import time from setuptools import setup # Folder",
"See the NOTICE file distributed with this work for additional",
"# Folder containing the setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path",
"= os.path.join(root, 'gremlin_python', '__version__.py') # Check if this is a",
"is a source distribution. # If not create the __version__",
"import __version__ version = __version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1',",
"not use this file except in compliance with the License.",
"NOTICE file distributed with this work for additional information regarding",
"Apache License, Version 2.0 (the \"License\"); you may not use",
"2.0 (the \"License\"); you may not use this file except",
"copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable",
"express or implied. See the License for the specific language",
"'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for",
"''' Licensed to the Apache Software Foundation (ASF) under one",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"Language :: Python :: 3.4\", \"Programming Language :: Python ::",
"to you under the Apache License, Version 2.0 (the \"License\");",
"in compliance with the License. You may obtain a copy",
"= [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info < (3,2):",
"of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law",
"OSI Approved :: Apache Software License\", \"Natural Language :: English\",",
"codecs import os import sys import time from setuptools import",
"to __version__ module version_file = os.path.join(root, 'gremlin_python', '__version__.py') # Check",
"1000)) / 1000 fd = codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__)",
"you may not use this file except in compliance with",
"import time from setuptools import setup # Folder containing the",
"setuptools import setup # Folder containing the setup.py root =",
"\"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest',",
"%r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp = %d\\n'",
"is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2',",
"the License. You may obtain a copy of the License",
"agreed to in writing, software distributed under the License is",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"from gremlin_python import __version__ version = __version__.version install_requires = [",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to",
"gremlin_python import __version__ version = __version__.version install_requires = [ 'aenum==1.4.5',",
"use this file except in compliance with the License. You",
"int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000 fd = codecs.open(version_file, 'w',",
"and limitations under the License. ''' import codecs import os",
"Apache Software Foundation (ASF) under one or more contributor license",
"the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or",
"\"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[",
"2.7\", \"Programming Language :: Python :: 3.4\", \"Programming Language ::",
"ANY KIND, either express or implied. See the License for",
"Python :: 2.7\", \"Programming Language :: Python :: 3.4\", \"Programming",
"http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in",
"Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[",
"may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless",
"obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required",
"Check if this is a source distribution. # If not",
"fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d'",
"one or more contributor license agreements. See the NOTICE file",
"'six==1.10.0' ] if sys.version_info < (3,2): install_requires += ['futures==3.0.5'] setup(",
"information regarding copyright ownership. The ASF licenses this file to",
"\"Programming Language :: Python :: 3.4\", \"Programming Language :: Python",
"version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org',",
"'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000 fd",
"sys import time from setuptools import setup # Folder containing",
"if sys.version_info < (3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version,",
"fd.write('version = %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp",
"either express or implied. See the License for the specific",
"ASF licenses this file to you under the Apache License,",
"timestamp) fd.close() # Load version from gremlin_python import __version__ version",
"setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[ \"Intended",
"<reponame>EvKissle/tinkerpop<gh_stars>0 ''' Licensed to the Apache Software Foundation (ASF) under",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"import codecs import os import sys import time from setuptools",
"'pytest', 'mock' ], install_requires=install_requires, classifiers=[ \"Intended Audience :: Developers\", \"License",
"under the License is distributed on an \"AS IS\" BASIS,",
"\"License\"); you may not use this file except in compliance",
"fd.write(\"'''\\n\") fd.write('version = %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp))",
"License is distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"= %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp =",
"\"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[",
":: 2.7\", \"Programming Language :: Python :: 3.4\", \"Programming Language",
"(3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado',",
"with the License. You may obtain a copy of the",
"Language :: English\", \"Programming Language :: Python :: 2.7\", \"Programming",
"The ASF licenses this file to you under the Apache",
"], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[ \"Intended Audience ::",
"file distributed with this work for additional information regarding copyright",
"fd = codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version =",
"License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed",
"contributor license agreements. See the NOTICE file distributed with this",
"fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n' % os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' %",
"version = __version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ]",
"License for the specific language governing permissions and limitations under",
"setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache",
"version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() *",
"containing the setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path to __version__",
"'?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp = %d\\n' % timestamp) fd.close()",
"__version__ module version_file = os.path.join(root, 'gremlin_python', '__version__.py') # Check if",
":: Python :: 2.7\", \"Programming Language :: Python :: 3.4\",",
"Audience :: Developers\", \"License :: OSI Approved :: Apache Software",
"< (3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver',",
"install_requires=install_requires, classifiers=[ \"Intended Audience :: Developers\", \"License :: OSI Approved",
"Apache Software License\", \"Natural Language :: English\", \"Programming Language ::",
"this file except in compliance with the License. You may",
"% timestamp)) fd.write('timestamp = %d\\n' % timestamp) fd.close() # Load",
"\"Intended Audience :: Developers\", \"License :: OSI Approved :: Apache",
"'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\",",
"additional information regarding copyright ownership. The ASF licenses this file",
"packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python",
"the setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module",
"= os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module version_file = os.path.join(root,",
"\"License :: OSI Approved :: Apache Software License\", \"Natural Language",
"(the \"License\"); you may not use this file except in",
"%d\\n' % timestamp) fd.close() # Load version from gremlin_python import",
"'pytest-runner', ], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[ \"Intended Audience",
"import os import sys import time from setuptools import setup",
"data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock' ],",
"codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n' %",
"the __version__ module containing the version if not os.path.exists(os.path.join(root, 'PKG-INFO')):",
"/ 1000 fd = codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\")",
"description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\",",
"Python :: 3.4\", \"Programming Language :: Python :: 3.5\", ]",
"'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\",",
"applicable law or agreed to in writing, software distributed under",
"root = os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module version_file =",
"'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info < (3,2): install_requires += ['futures==3.0.5']",
"= codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n'",
"Developers\", \"License :: OSI Approved :: Apache Software License\", \"Natural",
"tests_require=[ 'pytest', 'mock' ], install_requires=install_requires, classifiers=[ \"Intended Audience :: Developers\",",
"under the License. ''' import codecs import os import sys",
"setup # Folder containing the setup.py root = os.path.dirname(os.path.abspath(__file__)) #",
"the License is distributed on an \"AS IS\" BASIS, WITHOUT",
"not create the __version__ module containing the version if not",
"specific language governing permissions and limitations under the License. '''",
"You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0",
"the specific language governing permissions and limitations under the License.",
"__version__ version = __version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0'",
":: OSI Approved :: Apache Software License\", \"Natural Language ::",
"version from gremlin_python import __version__ version = __version__.version install_requires =",
"source distribution. # If not create the __version__ module containing",
"# Load version from gremlin_python import __version__ version = __version__.version",
"Load version from gremlin_python import __version__ version = __version__.version install_requires",
"License\", \"Natural Language :: English\", \"Programming Language :: Python ::",
"__version__ module containing the version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp",
"'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version = %r\\n' % os.getenv('VERSION',",
"'.dev-%d' % timestamp)) fd.write('timestamp = %d\\n' % timestamp) fd.close() #",
"os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000",
"the Apache License, Version 2.0 (the \"License\"); you may not",
"file except in compliance with the License. You may obtain",
"except in compliance with the License. You may obtain a",
"or implied. See the License for the specific language governing",
"KIND, either express or implied. See the License for the",
"this work for additional information regarding copyright ownership. The ASF",
"module version_file = os.path.join(root, 'gremlin_python', '__version__.py') # Check if this",
"os.path.join(root, 'gremlin_python', '__version__.py') # Check if this is a source",
"to in writing, software distributed under the License is distributed",
"a source distribution. # If not create the __version__ module",
"1000 fd = codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\") fd.write(__doc__) fd.write(\"'''\\n\") fd.write('version",
"= int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000 fd = codecs.open(version_file,",
"fd.close() # Load version from gremlin_python import __version__ version =",
"[ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info < (3,2): install_requires",
"the version if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time()",
"\"Programming Language :: Python :: 2.7\", \"Programming Language :: Python",
":: 3.4\", \"Programming Language :: Python :: 3.5\", ] )",
"or agreed to in writing, software distributed under the License",
"this file to you under the Apache License, Version 2.0",
"classifiers=[ \"Intended Audience :: Developers\", \"License :: OSI Approved ::",
"time.time() * 1000)) / 1000 fd = codecs.open(version_file, 'w', 'utf-8')",
"sys.version_info < (3,2): install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python',",
"law or agreed to in writing, software distributed under the",
"OR CONDITIONS OF ANY KIND, either express or implied. See",
"install_requires += ['futures==3.0.5'] setup( name='gremlinpython', version=version, packages=['gremlin_python', 'gremlin_python.driver', 'gremlin_python.driver.tornado', 'gremlin_python.process',",
"compliance with the License. You may obtain a copy of",
"under one or more contributor license agreements. See the NOTICE",
"license agreements. See the NOTICE file distributed with this work",
"'gremlin_python.driver.tornado', 'gremlin_python.process', 'gremlin_python.structure', 'gremlin_python.structure.io'], license='Apache 2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache",
"OF ANY KIND, either express or implied. See the License",
"under the Apache License, Version 2.0 (the \"License\"); you may",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"permissions and limitations under the License. ''' import codecs import",
"the License. ''' import codecs import os import sys import",
"if this is a source distribution. # If not create",
"* 1000)) / 1000 fd = codecs.open(version_file, 'w', 'utf-8') fd.write(\"'''\")",
"# Path to __version__ module version_file = os.path.join(root, 'gremlin_python', '__version__.py')",
"long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ],",
"test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock'",
"timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000)) / 1000 fd =",
"Software License\", \"Natural Language :: English\", \"Programming Language :: Python",
"os import sys import time from setuptools import setup #",
"fd.write('timestamp = %d\\n' % timestamp) fd.close() # Load version from",
"with this work for additional information regarding copyright ownership. The",
"timestamp)) fd.write('timestamp = %d\\n' % timestamp) fd.close() # Load version",
"# If not create the __version__ module containing the version",
"License, Version 2.0 (the \"License\"); you may not use this",
"import setup # Folder containing the setup.py root = os.path.dirname(os.path.abspath(__file__))",
"you under the Apache License, Version 2.0 (the \"License\"); you",
"url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\",",
"% os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp = %d\\n' %",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"for the specific language governing permissions and limitations under the",
"distribution. # If not create the __version__ module containing the",
"See the License for the specific language governing permissions and",
"= %d\\n' % timestamp) fd.close() # Load version from gremlin_python",
"TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\", data_files=[(\"\", [\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner',",
"a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by",
"(ASF) under one or more contributor license agreements. See the",
"if not os.path.exists(os.path.join(root, 'PKG-INFO')): timestamp = int(os.getenv('TIMESTAMP', time.time() * 1000))",
"], install_requires=install_requires, classifiers=[ \"Intended Audience :: Developers\", \"License :: OSI",
"Folder containing the setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path to",
"licenses this file to you under the Apache License, Version",
"If not create the __version__ module containing the version if",
"work for additional information regarding copyright ownership. The ASF licenses",
"create the __version__ module containing the version if not os.path.exists(os.path.join(root,",
"ownership. The ASF licenses this file to you under the",
"regarding copyright ownership. The ASF licenses this file to you",
"file to you under the Apache License, Version 2.0 (the",
"License. You may obtain a copy of the License at",
"os.getenv('VERSION', '?').replace('-SNAPSHOT', '.dev-%d' % timestamp)) fd.write('timestamp = %d\\n' % timestamp)",
"\"Natural Language :: English\", \"Programming Language :: Python :: 2.7\",",
"for additional information regarding copyright ownership. The ASF licenses this",
"'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info < (3,2): install_requires +=",
"the License for the specific language governing permissions and limitations",
"from setuptools import setup # Folder containing the setup.py root",
"may not use this file except in compliance with the",
"time from setuptools import setup # Folder containing the setup.py",
"= __version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if",
"''' import codecs import os import sys import time from",
"in writing, software distributed under the License is distributed on",
"2', url='http://tinkerpop.apache.org', description='Gremlin-Python for Apache TinkerPop', long_description=codecs.open(\"README\", \"r\", \"UTF-8\").read(), test_suite=\"tests\",",
"[\"LICENSE\", \"NOTICE\"])], setup_requires=[ 'pytest-runner', ], tests_require=[ 'pytest', 'mock' ], install_requires=install_requires,",
"required by applicable law or agreed to in writing, software",
":: Apache Software License\", \"Natural Language :: English\", \"Programming Language",
"implied. See the License for the specific language governing permissions",
":: English\", \"Programming Language :: Python :: 2.7\", \"Programming Language",
"__version__.version install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info",
"setup.py root = os.path.dirname(os.path.abspath(__file__)) # Path to __version__ module version_file",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"or more contributor license agreements. See the NOTICE file distributed",
"'gremlin_python', '__version__.py') # Check if this is a source distribution.",
"Approved :: Apache Software License\", \"Natural Language :: English\", \"Programming",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"copyright ownership. The ASF licenses this file to you under",
"the NOTICE file distributed with this work for additional information",
"language governing permissions and limitations under the License. ''' import",
"install_requires = [ 'aenum==1.4.5', 'tornado==4.4.1', 'six==1.10.0' ] if sys.version_info <",
":: Python :: 3.4\", \"Programming Language :: Python :: 3.5\",",
"Software Foundation (ASF) under one or more contributor license agreements.",
"English\", \"Programming Language :: Python :: 2.7\", \"Programming Language ::",
"distributed with this work for additional information regarding copyright ownership.",
"'__version__.py') # Check if this is a source distribution. #",
"'mock' ], install_requires=install_requires, classifiers=[ \"Intended Audience :: Developers\", \"License ::"
] |
[
"name: Optional[str] = None, show_legend: bool = False, show_init: bool",
"Show this trace initially. \"\"\" return go.Bar(x=x, y=y, text=text, width=width,",
"Coordinates of data on y-axis. optional arguments: @ col :",
"data on x-axis. @ y : Coordinates of data on",
"@ col : Color of bars. @ opacity : Opacity",
"show_legend : Show this trace in legend. @ show_init :",
"<reponame>yoshihikosuzuki/plotly_light<gh_stars>0 from typing import Optional, Sequence import plotly.graph_objects as go",
"-> go.Bar: \"\"\"Create a simple Trace object of a histogram.",
"positional arguments: @ x : Coordinates of data on x-axis.",
"initially. \"\"\" return go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name,",
"this trace initially. \"\"\" return go.Bar(x=x, y=y, text=text, width=width, marker_color=col,",
"in legend. @ show_init : Show this trace initially. \"\"\"",
"show_init : Show this trace initially. \"\"\" return go.Bar(x=x, y=y,",
"of data on x-axis. @ y : Coordinates of data",
": Opacity of bars. @ name : Display name of",
"name of the trace in legend. @ show_legend : Show",
"x : Coordinates of data on x-axis. @ y :",
"@ show_legend : Show this trace in legend. @ show_init",
"from typing import Optional, Sequence import plotly.graph_objects as go def",
"go.Bar: \"\"\"Create a simple Trace object of a histogram. positional",
"\"\"\" return go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend,",
"of bars. @ opacity : Opacity of bars. @ name",
"Optional[str] = None, show_legend: bool = False, show_init: bool =",
"\"\"\"Create a simple Trace object of a histogram. positional arguments:",
"def bar(x: Sequence, y: Sequence, text: Optional[Sequence] = None, width:",
"x-axis. @ y : Coordinates of data on y-axis. optional",
"Sequence, y: Sequence, text: Optional[Sequence] = None, width: Optional[int] =",
"Coordinates of data on x-axis. @ y : Coordinates of",
"legend. @ show_init : Show this trace initially. \"\"\" return",
"trace initially. \"\"\" return go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity,",
"opacity: float = 1, name: Optional[str] = None, show_legend: bool",
"data on y-axis. optional arguments: @ col : Color of",
"on y-axis. optional arguments: @ col : Color of bars.",
"typing import Optional, Sequence import plotly.graph_objects as go def bar(x:",
"Sequence import plotly.graph_objects as go def bar(x: Sequence, y: Sequence,",
"Optional[Sequence] = None, width: Optional[int] = None, col: Optional[str] =",
"Display name of the trace in legend. @ show_legend :",
"arguments: @ x : Coordinates of data on x-axis. @",
"= None, opacity: float = 1, name: Optional[str] = None,",
"return go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None",
"Opacity of bars. @ name : Display name of the",
"@ name : Display name of the trace in legend.",
"text: Optional[Sequence] = None, width: Optional[int] = None, col: Optional[str]",
"Optional, Sequence import plotly.graph_objects as go def bar(x: Sequence, y:",
"simple Trace object of a histogram. positional arguments: @ x",
"None, opacity: float = 1, name: Optional[str] = None, show_legend:",
"of the trace in legend. @ show_legend : Show this",
": Display name of the trace in legend. @ show_legend",
"None, col: Optional[str] = None, opacity: float = 1, name:",
"= None, show_legend: bool = False, show_init: bool = True)",
"show_legend: bool = False, show_init: bool = True) -> go.Bar:",
"@ show_init : Show this trace initially. \"\"\" return go.Bar(x=x,",
"import plotly.graph_objects as go def bar(x: Sequence, y: Sequence, text:",
"go.Bar(x=x, y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None if",
"@ y : Coordinates of data on y-axis. optional arguments:",
"False, show_init: bool = True) -> go.Bar: \"\"\"Create a simple",
"Optional[int] = None, col: Optional[str] = None, opacity: float =",
"col: Optional[str] = None, opacity: float = 1, name: Optional[str]",
"trace in legend. @ show_legend : Show this trace in",
": Coordinates of data on x-axis. @ y : Coordinates",
"legend. @ show_legend : Show this trace in legend. @",
"a simple Trace object of a histogram. positional arguments: @",
"bars. @ name : Display name of the trace in",
"as go def bar(x: Sequence, y: Sequence, text: Optional[Sequence] =",
"name : Display name of the trace in legend. @",
"y : Coordinates of data on y-axis. optional arguments: @",
"y=y, text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None if show_init",
"= None, width: Optional[int] = None, col: Optional[str] = None,",
"width: Optional[int] = None, col: Optional[str] = None, opacity: float",
"Optional[str] = None, opacity: float = 1, name: Optional[str] =",
"bar(x: Sequence, y: Sequence, text: Optional[Sequence] = None, width: Optional[int]",
"histogram. positional arguments: @ x : Coordinates of data on",
"= 1, name: Optional[str] = None, show_legend: bool = False,",
"arguments: @ col : Color of bars. @ opacity :",
"text=text, width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None if show_init else",
": Show this trace initially. \"\"\" return go.Bar(x=x, y=y, text=text,",
"= True) -> go.Bar: \"\"\"Create a simple Trace object of",
"the trace in legend. @ show_legend : Show this trace",
"y: Sequence, text: Optional[Sequence] = None, width: Optional[int] = None,",
"@ x : Coordinates of data on x-axis. @ y",
"1, name: Optional[str] = None, show_legend: bool = False, show_init:",
"go def bar(x: Sequence, y: Sequence, text: Optional[Sequence] = None,",
"col : Color of bars. @ opacity : Opacity of",
"opacity : Opacity of bars. @ name : Display name",
"True) -> go.Bar: \"\"\"Create a simple Trace object of a",
"float = 1, name: Optional[str] = None, show_legend: bool =",
"Show this trace in legend. @ show_init : Show this",
": Coordinates of data on y-axis. optional arguments: @ col",
"optional arguments: @ col : Color of bars. @ opacity",
"bars. @ opacity : Opacity of bars. @ name :",
"object of a histogram. positional arguments: @ x : Coordinates",
"plotly.graph_objects as go def bar(x: Sequence, y: Sequence, text: Optional[Sequence]",
": Show this trace in legend. @ show_init : Show",
"y-axis. optional arguments: @ col : Color of bars. @",
"@ opacity : Opacity of bars. @ name : Display",
"= None, col: Optional[str] = None, opacity: float = 1,",
"None, width: Optional[int] = None, col: Optional[str] = None, opacity:",
"Trace object of a histogram. positional arguments: @ x :",
"trace in legend. @ show_init : Show this trace initially.",
"a histogram. positional arguments: @ x : Coordinates of data",
"this trace in legend. @ show_init : Show this trace",
"of a histogram. positional arguments: @ x : Coordinates of",
"width=width, marker_color=col, opacity=opacity, name=name, showlegend=show_legend, visible=None if show_init else \"legendonly\")",
"= False, show_init: bool = True) -> go.Bar: \"\"\"Create a",
"of data on y-axis. optional arguments: @ col : Color",
"on x-axis. @ y : Coordinates of data on y-axis.",
"bool = True) -> go.Bar: \"\"\"Create a simple Trace object",
"Sequence, text: Optional[Sequence] = None, width: Optional[int] = None, col:",
"None, show_legend: bool = False, show_init: bool = True) ->",
"Color of bars. @ opacity : Opacity of bars. @",
": Color of bars. @ opacity : Opacity of bars.",
"show_init: bool = True) -> go.Bar: \"\"\"Create a simple Trace",
"of bars. @ name : Display name of the trace",
"bool = False, show_init: bool = True) -> go.Bar: \"\"\"Create",
"import Optional, Sequence import plotly.graph_objects as go def bar(x: Sequence,",
"in legend. @ show_legend : Show this trace in legend."
] |
[
"acts upon. wires (Iterable): wires that the template acts on",
"acts on \"\"\" num_params = 1 num_wires = AnyWires par_domain",
"2.0 (the \"License\"); # you may not use this file",
"tensor. Args: n_wires (int): number of wires that template acts",
"be greater than zero. start (int, optional): Optional start of",
"1 num_wires = AnyWires par_domain = \"A\" def __init__(self, weights,",
"do_queue=do_queue, id=id) def expand(self): weights = self.parameters[0] with qml.tape.QuantumTape() as",
"range(k): base_repesentation.append(val % n) val //= n shift = 0",
"k base_repesentation = [] val = i for j in",
"than zero. start (int, optional): Optional start of the Gray",
"Gray code with k digits. Args: n (int): Base of",
"Operation, AnyWires from pennylane.ops import PauliRot _PAULIS = [\"I\", \"X\",",
"in range(start, n ** k): codeword = [0] * k",
"over a full n-ary Gray code with k digits. Args:",
"in _n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary",
"use this file except in compliance with the License. #",
"number of wires the template acts upon. wires (Iterable): wires",
"word rotations, needs to have length :math:`4^n - 1` where",
"Gray code. Needs to be greater than zero. start (int,",
"n_wires (int): number of wires that template acts on \"\"\"",
"a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless",
"template acts upon. wires (Iterable): wires that the template acts",
"can be used as a building block, e.g. to parametrize",
"wires that template acts on \"\"\" return (4 ** n_wires",
"be used as a building block, e.g. to parametrize arbitrary",
"in a circuit: .. code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires):",
"+= n - codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires): # Start",
"% n) val //= n shift = 0 for j",
"License. # You may obtain a copy of the License",
"the specified wires. An arbitrary unitary on :math:`n` wires is",
"have length :math:`4^n - 1` where :math:`n` is the number",
"to ignore identity yield from (_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4,",
"Quantum Technologies Inc. # Licensed under the Apache License, Version",
"under the License is distributed on an \"AS IS\" BASIS,",
"yield from (_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4, num_wires, start=1)) class",
"License for the specific language governing permissions and # limitations",
"Args: index_tuple (Tuple[int]): An integer tuple describing the Pauli word",
"id=None): shape = qml.math.shape(weights) if shape != (4 ** len(wires)",
"Needs to be greater than zero. start (int, optional): Optional",
"of shape {(4 ** len(wires) - 1,)}; got {shape}.\" )",
"word rotations to parametrize the unitary. **Example** ArbitraryUnitary can be",
"be greater than one. k (int): Number of digits of",
"describing the Pauli word Returns: str: The corresponding Pauli word",
".. code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires,",
"yield codeword def _all_pauli_words_but_identity(num_wires): # Start at 1 to ignore",
"weights tensor. Args: n_wires (int): number of wires that template",
"_tuple_to_word(index_tuple): \"\"\"Convert an integer tuple to the corresponding Pauli word.",
"at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or",
"def _n_k_gray_code(n, k, start=0): \"\"\"Iterates over a full n-ary Gray",
"Gray code. The generated code will be shorter as the",
"0. \"\"\" for i in range(start, n ** k): codeword",
"val = i for j in range(k): base_repesentation.append(val % n)",
"operators are converted as ``0 -> I``, ``1 -> X``,",
"as ``0 -> I``, ``1 -> X``, ``2 -> Y``,",
"1` independent real parameters. This templates uses Pauli word rotations",
"as the code does not wrap. Defaults to 0. \"\"\"",
"in compliance with the License. # You may obtain a",
"wires is parametrized by :math:`4^n - 1` independent real parameters.",
"software # distributed under the License is distributed on an",
"shape of the weights tensor. Args: n_wires (int): number of",
"parametrize arbitrary two-qubit operations in a circuit: .. code-block:: python",
"python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args:",
"** k): codeword = [0] * k base_repesentation = []",
"converted as ``0 -> I``, ``1 -> X``, ``2 ->",
"to 0. \"\"\" for i in range(start, n ** k):",
"from pennylane.operation import Operation, AnyWires from pennylane.ops import PauliRot _PAULIS",
"\"\"\"Convert an integer tuple to the corresponding Pauli word. The",
"n) val //= n shift = 0 for j in",
"``1 -> X``, ``2 -> Y``, ``3 -> Z``. Args:",
"qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args: weights (tensor_like): The angles of",
"import pennylane as qml from pennylane.operation import Operation, AnyWires from",
"limitations under the License. r\"\"\" Contains the ArbitraryUnitary template. \"\"\"",
"to the corresponding Pauli word. The Pauli operators are converted",
"super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def expand(self): weights = self.parameters[0] with",
"arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args: weights (tensor_like): The",
"if shape != (4 ** len(wires) - 1,): raise ValueError(",
"length :math:`4^n - 1` where :math:`n` is the number of",
"n shift = 0 for j in reversed(range(k)): codeword[j] =",
"\"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an integer tuple to",
"used as a building block, e.g. to parametrize arbitrary two-qubit",
"[\"I\", \"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an integer tuple",
"the unitary. **Example** ArbitraryUnitary can be used as a building",
"parameters. This templates uses Pauli word rotations to parametrize the",
"identity yield from (_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4, num_wires, start=1))",
"OF ANY KIND, either express or implied. # See the",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"code with k digits. Args: n (int): Base of the",
"template. \"\"\" import pennylane as qml from pennylane.operation import Operation,",
"An arbitrary unitary on :math:`n` wires is parametrized by :math:`4^n",
"ANY KIND, either express or implied. # See the License",
"See the License for the specific language governing permissions and",
"qml from pennylane.operation import Operation, AnyWires from pennylane.ops import PauliRot",
"the License. # You may obtain a copy of the",
"for the specific language governing permissions and # limitations under",
"to in writing, software # distributed under the License is",
"- 1,)}; got {shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def",
"# See the License for the specific language governing permissions",
"where :math:`n` is the number of wires the template acts",
"in reversed(range(k)): codeword[j] = (base_repesentation[j] + shift) % n shift",
"or agreed to in writing, software # distributed under the",
"required by applicable law or agreed to in writing, software",
"def shape(n_wires): \"\"\"Compute the expected shape of the weights tensor.",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"The angles of the Pauli word rotations, needs to have",
"shift += n - codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires): #",
"with the License. # You may obtain a copy of",
"= 0 for j in reversed(range(k)): codeword[j] = (base_repesentation[j] +",
"e.g. to parametrize arbitrary two-qubit operations in a circuit: ..",
"operations in a circuit: .. code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights,",
"shape {(4 ** len(wires) - 1,)}; got {shape}.\" ) super().__init__(weights,",
"**Example** ArbitraryUnitary can be used as a building block, e.g.",
"# Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under",
"of the Gray code. Needs to be greater than zero.",
"par_domain = \"A\" def __init__(self, weights, wires, do_queue=True, id=None): shape",
"to have length :math:`4^n - 1` where :math:`n` is the",
"AnyWires from pennylane.ops import PauliRot _PAULIS = [\"I\", \"X\", \"Y\",",
"Number of digits of the Gray code. Needs to be",
"compliance with the License. # You may obtain a copy",
"agreed to in writing, software # distributed under the License",
"pennylane.operation import Operation, AnyWires from pennylane.ops import PauliRot _PAULIS =",
":math:`n` is the number of wires the template acts upon.",
"wires=wires, params=weights) Args: weights (tensor_like): The angles of the Pauli",
"of the Gray code. The generated code will be shorter",
"n-ary Gray code with k digits. Args: n (int): Base",
"val //= n shift = 0 for j in reversed(range(k)):",
"distributed under the License is distributed on an \"AS IS\"",
"with k digits. Args: n (int): Base of the Gray",
"real parameters. This templates uses Pauli word rotations to parametrize",
"__init__(self, weights, wires, do_queue=True, id=None): shape = qml.math.shape(weights) if shape",
"arbitrary unitary on :math:`n` wires is parametrized by :math:`4^n -",
"Args: weights (tensor_like): The angles of the Pauli word rotations,",
"= (base_repesentation[j] + shift) % n shift += n -",
"express or implied. # See the License for the specific",
"i in range(start, n ** k): codeword = [0] *",
"except in compliance with the License. # You may obtain",
"the expected shape of the weights tensor. Args: n_wires (int):",
"Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"//= n shift = 0 for j in reversed(range(k)): codeword[j]",
"not use this file except in compliance with the License.",
"rotations, needs to have length :math:`4^n - 1` where :math:`n`",
"in range(k): base_repesentation.append(val % n) val //= n shift =",
"writing, software # distributed under the License is distributed on",
"wires=wires, do_queue=do_queue, id=id) def expand(self): weights = self.parameters[0] with qml.tape.QuantumTape()",
"1 to ignore identity yield from (_tuple_to_word(idx_tuple) for idx_tuple in",
"parametrize the unitary. **Example** ArbitraryUnitary can be used as a",
"you may not use this file except in compliance with",
"# Licensed under the Apache License, Version 2.0 (the \"License\");",
") super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def expand(self): weights = self.parameters[0]",
"codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires): # Start at 1 to",
"= AnyWires par_domain = \"A\" def __init__(self, weights, wires, do_queue=True,",
"Args: n (int): Base of the Gray code. Needs to",
"Pauli word. The Pauli operators are converted as ``0 ->",
"does not wrap. Defaults to 0. \"\"\" for i in",
"codeword = [0] * k base_repesentation = [] val =",
"block, e.g. to parametrize arbitrary two-qubit operations in a circuit:",
"= [] val = i for j in range(k): base_repesentation.append(val",
"a circuit: .. code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary,",
"CONDITIONS OF ANY KIND, either express or implied. # See",
"def _tuple_to_word(index_tuple): \"\"\"Convert an integer tuple to the corresponding Pauli",
"as qml from pennylane.operation import Operation, AnyWires from pennylane.ops import",
"_all_pauli_words_but_identity(num_wires): # Start at 1 to ignore identity yield from",
"Pauli operators are converted as ``0 -> I``, ``1 ->",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"Returns: str: The corresponding Pauli word \"\"\" return \"\".join([_PAULIS[i] for",
"Base of the Gray code. Needs to be greater than",
"Start at 1 to ignore identity yield from (_tuple_to_word(idx_tuple) for",
"the template acts on \"\"\" num_params = 1 num_wires =",
"the number of wires the template acts upon. wires (Iterable):",
"as tape: for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires)",
"greater than zero. start (int, optional): Optional start of the",
"http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed to",
"from pennylane.ops import PauliRot _PAULIS = [\"I\", \"X\", \"Y\", \"Z\"]",
"range(start, n ** k): codeword = [0] * k base_repesentation",
"arbitrary two-qubit operations in a circuit: .. code-block:: python @qml.template",
"_PAULIS = [\"I\", \"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an",
"= 1 num_wires = AnyWires par_domain = \"A\" def __init__(self,",
"self.parameters[0] with qml.tape.QuantumTape() as tape: for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))):",
"that template acts on \"\"\" return (4 ** n_wires -",
"specified wires. An arbitrary unitary on :math:`n` wires is parametrized",
"0 for j in reversed(range(k)): codeword[j] = (base_repesentation[j] + shift)",
"of the Pauli word rotations, needs to have length :math:`4^n",
"@qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args: weights",
"pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return tape @staticmethod def",
"def expand(self): weights = self.parameters[0] with qml.tape.QuantumTape() as tape: for",
"for j in range(k): base_repesentation.append(val % n) val //= n",
"!= (4 ** len(wires) - 1,): raise ValueError( f\"Weights tensor",
"OR CONDITIONS OF ANY KIND, either express or implied. #",
"the License is distributed on an \"AS IS\" BASIS, #",
"be shorter as the code does not wrap. Defaults to",
"-> X``, ``2 -> Y``, ``3 -> Z``. Args: index_tuple",
"codeword[j] = (base_repesentation[j] + shift) % n shift += n",
"\"\"\" return \"\".join([_PAULIS[i] for i in index_tuple]) def _n_k_gray_code(n, k,",
"start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary on the specified",
"angles of the Pauli word rotations, needs to have length",
"qml.tape.QuantumTape() as tape: for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word,",
"templates uses Pauli word rotations to parametrize the unitary. **Example**",
"Inc. # Licensed under the Apache License, Version 2.0 (the",
"integer tuple to the corresponding Pauli word. The Pauli operators",
"uses Pauli word rotations to parametrize the unitary. **Example** ArbitraryUnitary",
"index_tuple (Tuple[int]): An integer tuple describing the Pauli word Returns:",
"be of shape {(4 ** len(wires) - 1,)}; got {shape}.\"",
"ValueError( f\"Weights tensor must be of shape {(4 ** len(wires)",
"i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return tape @staticmethod",
"shorter as the code does not wrap. Defaults to 0.",
"greater than one. k (int): Number of digits of the",
"\"\"\" num_params = 1 num_wires = AnyWires par_domain = \"A\"",
"Gray code. Needs to be greater than one. k (int):",
"digits. Args: n (int): Base of the Gray code. Needs",
"from (_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation):",
"- 1,): raise ValueError( f\"Weights tensor must be of shape",
"law or agreed to in writing, software # distributed under",
"The generated code will be shorter as the code does",
"building block, e.g. to parametrize arbitrary two-qubit operations in a",
"on :math:`n` wires is parametrized by :math:`4^n - 1` independent",
"(int): Number of digits of the Gray code. Needs to",
"an arbitrary unitary on the specified wires. An arbitrary unitary",
"-> Y``, ``3 -> Z``. Args: index_tuple (Tuple[int]): An integer",
"``3 -> Z``. Args: index_tuple (Tuple[int]): An integer tuple describing",
"License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law",
"of wires the template acts upon. wires (Iterable): wires that",
"\"A\" def __init__(self, weights, wires, do_queue=True, id=None): shape = qml.math.shape(weights)",
"pattern=\"double\", wires=wires, params=weights) Args: weights (tensor_like): The angles of the",
"code. The generated code will be shorter as the code",
"+ shift) % n shift += n - codeword[j] yield",
"index_tuple]) def _n_k_gray_code(n, k, start=0): \"\"\"Iterates over a full n-ary",
"shift) % n shift += n - codeword[j] yield codeword",
"import Operation, AnyWires from pennylane.ops import PauliRot _PAULIS = [\"I\",",
"n - codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires): # Start at",
"n shift += n - codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires):",
"for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return tape",
"num_params = 1 num_wires = AnyWires par_domain = \"A\" def",
"expected shape of the weights tensor. Args: n_wires (int): number",
"do_queue=True, id=None): shape = qml.math.shape(weights) if shape != (4 **",
"(int): number of wires that template acts on \"\"\" return",
"the Pauli word rotations, needs to have length :math:`4^n -",
"codeword def _all_pauli_words_but_identity(num_wires): # Start at 1 to ignore identity",
"qml.math.shape(weights) if shape != (4 ** len(wires) - 1,): raise",
"pennylane as qml from pennylane.operation import Operation, AnyWires from pennylane.ops",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"n (int): Base of the Gray code. Needs to be",
"code will be shorter as the code does not wrap.",
"wires=self.wires) return tape @staticmethod def shape(n_wires): \"\"\"Compute the expected shape",
"corresponding Pauli word \"\"\" return \"\".join([_PAULIS[i] for i in index_tuple])",
"may not use this file except in compliance with the",
"got {shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def expand(self): weights",
"for idx_tuple in _n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"% n shift += n - codeword[j] yield codeword def",
"this file except in compliance with the License. # You",
"- codeword[j] yield codeword def _all_pauli_words_but_identity(num_wires): # Start at 1",
"\"\"\"Compute the expected shape of the weights tensor. Args: n_wires",
"word. The Pauli operators are converted as ``0 -> I``,",
"(int, optional): Optional start of the Gray code. The generated",
"PauliRot(weights[i], pauli_word, wires=self.wires) return tape @staticmethod def shape(n_wires): \"\"\"Compute the",
"zero. start (int, optional): Optional start of the Gray code.",
"the template acts upon. wires (Iterable): wires that the template",
"k (int): Number of digits of the Gray code. Needs",
"file except in compliance with the License. # You may",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"Defaults to 0. \"\"\" for i in range(start, n **",
"\"\".join([_PAULIS[i] for i in index_tuple]) def _n_k_gray_code(n, k, start=0): \"\"\"Iterates",
"code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights)",
"wires, do_queue=True, id=None): shape = qml.math.shape(weights) if shape != (4",
"to parametrize arbitrary two-qubit operations in a circuit: .. code-block::",
"unitary on the specified wires. An arbitrary unitary on :math:`n`",
"tape @staticmethod def shape(n_wires): \"\"\"Compute the expected shape of the",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"# Start at 1 to ignore identity yield from (_tuple_to_word(idx_tuple)",
"Pauli word \"\"\" return \"\".join([_PAULIS[i] for i in index_tuple]) def",
"is parametrized by :math:`4^n - 1` independent real parameters. This",
"raise ValueError( f\"Weights tensor must be of shape {(4 **",
"pennylane.ops import PauliRot _PAULIS = [\"I\", \"X\", \"Y\", \"Z\"] def",
"full n-ary Gray code with k digits. Args: n (int):",
"Y``, ``3 -> Z``. Args: index_tuple (Tuple[int]): An integer tuple",
"wires (Iterable): wires that the template acts on \"\"\" num_params",
"of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by",
"ArbitraryUnitary template. \"\"\" import pennylane as qml from pennylane.operation import",
"(Tuple[int]): An integer tuple describing the Pauli word Returns: str:",
"under the License. r\"\"\" Contains the ArbitraryUnitary template. \"\"\" import",
"Optional start of the Gray code. The generated code will",
"or implied. # See the License for the specific language",
"the License. r\"\"\" Contains the ArbitraryUnitary template. \"\"\" import pennylane",
"str: The corresponding Pauli word \"\"\" return \"\".join([_PAULIS[i] for i",
"KIND, either express or implied. # See the License for",
"specific language governing permissions and # limitations under the License.",
"in index_tuple]) def _n_k_gray_code(n, k, start=0): \"\"\"Iterates over a full",
"for i in range(start, n ** k): codeword = [0]",
"k digits. Args: n (int): Base of the Gray code.",
"to be greater than one. k (int): Number of digits",
"by :math:`4^n - 1` independent real parameters. This templates uses",
"to parametrize the unitary. **Example** ArbitraryUnitary can be used as",
"ignore identity yield from (_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4, num_wires,",
"= [0] * k base_repesentation = [] val = i",
"a building block, e.g. to parametrize arbitrary two-qubit operations in",
":math:`4^n - 1` independent real parameters. This templates uses Pauli",
"return \"\".join([_PAULIS[i] for i in index_tuple]) def _n_k_gray_code(n, k, start=0):",
"- 1` independent real parameters. This templates uses Pauli word",
"the Pauli word Returns: str: The corresponding Pauli word \"\"\"",
":math:`4^n - 1` where :math:`n` is the number of wires",
"AnyWires par_domain = \"A\" def __init__(self, weights, wires, do_queue=True, id=None):",
"The Pauli operators are converted as ``0 -> I``, ``1",
"PauliRot _PAULIS = [\"I\", \"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert",
"code does not wrap. Defaults to 0. \"\"\" for i",
"import PauliRot _PAULIS = [\"I\", \"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple):",
"(_tuple_to_word(idx_tuple) for idx_tuple in _n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements",
"k, start=0): \"\"\"Iterates over a full n-ary Gray code with",
"copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required",
"wires. An arbitrary unitary on :math:`n` wires is parametrized by",
"(the \"License\"); # you may not use this file except",
"[0] * k base_repesentation = [] val = i for",
"start of the Gray code. The generated code will be",
"-> I``, ``1 -> X``, ``2 -> Y``, ``3 ->",
"_n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary on",
"# you may not use this file except in compliance",
"(Iterable): wires that the template acts on \"\"\" num_params =",
"as a building block, e.g. to parametrize arbitrary two-qubit operations",
":math:`n` wires is parametrized by :math:`4^n - 1` independent real",
"are converted as ``0 -> I``, ``1 -> X``, ``2",
"= i for j in range(k): base_repesentation.append(val % n) val",
"base_repesentation.append(val % n) val //= n shift = 0 for",
"with qml.tape.QuantumTape() as tape: for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i],",
"``0 -> I``, ``1 -> X``, ``2 -> Y``, ``3",
"f\"Weights tensor must be of shape {(4 ** len(wires) -",
"permissions and # limitations under the License. r\"\"\" Contains the",
"at 1 to ignore identity yield from (_tuple_to_word(idx_tuple) for idx_tuple",
"num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary on the",
"This templates uses Pauli word rotations to parametrize the unitary.",
"n ** k): codeword = [0] * k base_repesentation =",
"class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary on the specified wires.",
"Version 2.0 (the \"License\"); # you may not use this",
"return tape @staticmethod def shape(n_wires): \"\"\"Compute the expected shape of",
"start=0): \"\"\"Iterates over a full n-ary Gray code with k",
"Pauli word rotations to parametrize the unitary. **Example** ArbitraryUnitary can",
"may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0",
"wires that the template acts on \"\"\" num_params = 1",
"X``, ``2 -> Y``, ``3 -> Z``. Args: index_tuple (Tuple[int]):",
"Needs to be greater than one. k (int): Number of",
"template acts on \"\"\" num_params = 1 num_wires = AnyWires",
"the weights tensor. Args: n_wires (int): number of wires that",
"implied. # See the License for the specific language governing",
"k): codeword = [0] * k base_repesentation = [] val",
"under the Apache License, Version 2.0 (the \"License\"); # you",
"``2 -> Y``, ``3 -> Z``. Args: index_tuple (Tuple[int]): An",
"digits of the Gray code. Needs to be greater than",
"= \"A\" def __init__(self, weights, wires, do_queue=True, id=None): shape =",
"ArbitraryUnitary can be used as a building block, e.g. to",
"\"\"\" import pennylane as qml from pennylane.operation import Operation, AnyWires",
"governing permissions and # limitations under the License. r\"\"\" Contains",
"code. Needs to be greater than zero. start (int, optional):",
"(base_repesentation[j] + shift) % n shift += n - codeword[j]",
"idx_tuple in _n_k_gray_code(4, num_wires, start=1)) class ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary",
"by applicable law or agreed to in writing, software #",
"* k base_repesentation = [] val = i for j",
"<reponame>doomhammerhell/pennylane # Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed",
"Args: n_wires (int): number of wires that template acts on",
"\"\"\"Iterates over a full n-ary Gray code with k digits.",
"params=weights) Args: weights (tensor_like): The angles of the Pauli word",
"template acts on \"\"\" return (4 ** n_wires - 1,)",
"wires the template acts upon. wires (Iterable): wires that the",
"the License at # http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable",
"\"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an integer tuple to the corresponding",
"ArbitraryUnitary(Operation): \"\"\"Implements an arbitrary unitary on the specified wires. An",
"must be of shape {(4 ** len(wires) - 1,)}; got",
"tuple describing the Pauli word Returns: str: The corresponding Pauli",
"# http://www.apache.org/licenses/LICENSE-2.0 # Unless required by applicable law or agreed",
"1,)}; got {shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def expand(self):",
"the Gray code. Needs to be greater than one. k",
"tuple to the corresponding Pauli word. The Pauli operators are",
"{(4 ** len(wires) - 1,)}; got {shape}.\" ) super().__init__(weights, wires=wires,",
"j in range(k): base_repesentation.append(val % n) val //= n shift",
"circuit: .. code-block:: python @qml.template def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\",",
"in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return tape @staticmethod def shape(n_wires):",
"def arbitrary_nearest_neighbour_interaction(weights, wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args: weights (tensor_like):",
"(int): Base of the Gray code. Needs to be greater",
"on the specified wires. An arbitrary unitary on :math:`n` wires",
"base_repesentation = [] val = i for j in range(k):",
"word Returns: str: The corresponding Pauli word \"\"\" return \"\".join([_PAULIS[i]",
"id=id) def expand(self): weights = self.parameters[0] with qml.tape.QuantumTape() as tape:",
"of wires that template acts on \"\"\" return (4 **",
"r\"\"\" Contains the ArbitraryUnitary template. \"\"\" import pennylane as qml",
"arbitrary unitary on the specified wires. An arbitrary unitary on",
"the ArbitraryUnitary template. \"\"\" import pennylane as qml from pennylane.operation",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"Unless required by applicable law or agreed to in writing,",
"than one. k (int): Number of digits of the Gray",
"1` where :math:`n` is the number of wires the template",
"License. r\"\"\" Contains the ArbitraryUnitary template. \"\"\" import pennylane as",
"the specific language governing permissions and # limitations under the",
"applicable law or agreed to in writing, software # distributed",
"a full n-ary Gray code with k digits. Args: n",
"Pauli word rotations, needs to have length :math:`4^n - 1`",
"and # limitations under the License. r\"\"\" Contains the ArbitraryUnitary",
"optional): Optional start of the Gray code. The generated code",
"unitary on :math:`n` wires is parametrized by :math:`4^n - 1`",
"The corresponding Pauli word \"\"\" return \"\".join([_PAULIS[i] for i in",
"shape(n_wires): \"\"\"Compute the expected shape of the weights tensor. Args:",
"Pauli word Returns: str: The corresponding Pauli word \"\"\" return",
"independent real parameters. This templates uses Pauli word rotations to",
"in writing, software # distributed under the License is distributed",
"Copyright 2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the",
"_n_k_gray_code(n, k, start=0): \"\"\"Iterates over a full n-ary Gray code",
"Technologies Inc. # Licensed under the Apache License, Version 2.0",
"An integer tuple describing the Pauli word Returns: str: The",
"needs to have length :math:`4^n - 1` where :math:`n` is",
"def __init__(self, weights, wires, do_queue=True, id=None): shape = qml.math.shape(weights) if",
"\"\"\" for i in range(start, n ** k): codeword =",
"(4 ** len(wires) - 1,): raise ValueError( f\"Weights tensor must",
"\"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an integer tuple to the",
"= self.parameters[0] with qml.tape.QuantumTape() as tape: for i, pauli_word in",
"** len(wires) - 1,): raise ValueError( f\"Weights tensor must be",
"def _all_pauli_words_but_identity(num_wires): # Start at 1 to ignore identity yield",
"start (int, optional): Optional start of the Gray code. The",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"License, Version 2.0 (the \"License\"); # you may not use",
"Xanadu Quantum Technologies Inc. # Licensed under the Apache License,",
"# You may obtain a copy of the License at",
"Contains the ArbitraryUnitary template. \"\"\" import pennylane as qml from",
"the corresponding Pauli word. The Pauli operators are converted as",
"reversed(range(k)): codeword[j] = (base_repesentation[j] + shift) % n shift +=",
"the Gray code. The generated code will be shorter as",
"weights = self.parameters[0] with qml.tape.QuantumTape() as tape: for i, pauli_word",
"@staticmethod def shape(n_wires): \"\"\"Compute the expected shape of the weights",
"word \"\"\" return \"\".join([_PAULIS[i] for i in index_tuple]) def _n_k_gray_code(n,",
"is the number of wires the template acts upon. wires",
"not wrap. Defaults to 0. \"\"\" for i in range(start,",
"j in reversed(range(k)): codeword[j] = (base_repesentation[j] + shift) % n",
"for i in index_tuple]) def _n_k_gray_code(n, k, start=0): \"\"\"Iterates over",
"the License for the specific language governing permissions and #",
"\"\"\"Implements an arbitrary unitary on the specified wires. An arbitrary",
"an integer tuple to the corresponding Pauli word. The Pauli",
"shape != (4 ** len(wires) - 1,): raise ValueError( f\"Weights",
"Apache License, Version 2.0 (the \"License\"); # you may not",
"number of wires that template acts on \"\"\" return (4",
"either express or implied. # See the License for the",
"I``, ``1 -> X``, ``2 -> Y``, ``3 -> Z``.",
"on \"\"\" num_params = 1 num_wires = AnyWires par_domain =",
"one. k (int): Number of digits of the Gray code.",
"i for j in range(k): base_repesentation.append(val % n) val //=",
"upon. wires (Iterable): wires that the template acts on \"\"\"",
"tensor must be of shape {(4 ** len(wires) - 1,)};",
"# limitations under the License. r\"\"\" Contains the ArbitraryUnitary template.",
"wrap. Defaults to 0. \"\"\" for i in range(start, n",
"that the template acts on \"\"\" num_params = 1 num_wires",
"rotations to parametrize the unitary. **Example** ArbitraryUnitary can be used",
"obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 #",
"len(wires) - 1,)}; got {shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue, id=id)",
"language governing permissions and # limitations under the License. r\"\"\"",
"the Gray code. Needs to be greater than zero. start",
"expand(self): weights = self.parameters[0] with qml.tape.QuantumTape() as tape: for i,",
"{shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue, id=id) def expand(self): weights =",
"two-qubit operations in a circuit: .. code-block:: python @qml.template def",
"-> Z``. Args: index_tuple (Tuple[int]): An integer tuple describing the",
"- 1` where :math:`n` is the number of wires the",
"shift = 0 for j in reversed(range(k)): codeword[j] = (base_repesentation[j]",
"num_wires = AnyWires par_domain = \"A\" def __init__(self, weights, wires,",
"code. Needs to be greater than one. k (int): Number",
"wires): qml.broadcast(unitary=ArbitraryUnitary, pattern=\"double\", wires=wires, params=weights) Args: weights (tensor_like): The angles",
"corresponding Pauli word. The Pauli operators are converted as ``0",
"integer tuple describing the Pauli word Returns: str: The corresponding",
"** len(wires) - 1,)}; got {shape}.\" ) super().__init__(weights, wires=wires, do_queue=do_queue,",
"unitary. **Example** ArbitraryUnitary can be used as a building block,",
"i in index_tuple]) def _n_k_gray_code(n, k, start=0): \"\"\"Iterates over a",
"[] val = i for j in range(k): base_repesentation.append(val %",
"\"License\"); # you may not use this file except in",
"2018-2021 Xanadu Quantum Technologies Inc. # Licensed under the Apache",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return tape @staticmethod def shape(n_wires): \"\"\"Compute",
"pauli_word, wires=self.wires) return tape @staticmethod def shape(n_wires): \"\"\"Compute the expected",
"weights (tensor_like): The angles of the Pauli word rotations, needs",
"# distributed under the License is distributed on an \"AS",
"to be greater than zero. start (int, optional): Optional start",
"# Unless required by applicable law or agreed to in",
"Z``. Args: index_tuple (Tuple[int]): An integer tuple describing the Pauli",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"1,): raise ValueError( f\"Weights tensor must be of shape {(4",
"(tensor_like): The angles of the Pauli word rotations, needs to",
"generated code will be shorter as the code does not",
"of the Gray code. Needs to be greater than one.",
"parametrized by :math:`4^n - 1` independent real parameters. This templates",
"You may obtain a copy of the License at #",
"tape: for i, pauli_word in enumerate(_all_pauli_words_but_identity(len(self.wires))): PauliRot(weights[i], pauli_word, wires=self.wires) return",
"will be shorter as the code does not wrap. Defaults",
"weights, wires, do_queue=True, id=None): shape = qml.math.shape(weights) if shape !=",
"the code does not wrap. Defaults to 0. \"\"\" for",
"of digits of the Gray code. Needs to be greater",
"= [\"I\", \"X\", \"Y\", \"Z\"] def _tuple_to_word(index_tuple): \"\"\"Convert an integer",
"len(wires) - 1,): raise ValueError( f\"Weights tensor must be of",
"shape = qml.math.shape(weights) if shape != (4 ** len(wires) -",
"the Apache License, Version 2.0 (the \"License\"); # you may",
"of the weights tensor. Args: n_wires (int): number of wires",
"= qml.math.shape(weights) if shape != (4 ** len(wires) - 1,):",
"for j in reversed(range(k)): codeword[j] = (base_repesentation[j] + shift) %"
] |
[
"class Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 32,",
"= self.conv_layers(imgs) out = nn.Flatten()(out) mu = self.mu_layer(out) logvar =",
"out.view(-1, 64, 8, 8) recon_img = self.deconv_layers(out) return recon_img class",
"return recon_img def sample(self, num_samples=64): z = torch.randn(num_samples, 200) samples",
"nn.Linear(4096, 200) def forward(self, imgs): out = self.conv_layers(imgs) out =",
"recon_img class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder = Encoder() self.decoder",
"class Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input = nn.Linear(200, 4096) self.deconv_layers",
"nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer =",
"configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005) return optimizer def training_step(self, train_batch,",
"+ kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return loss",
"logvar = self.encoder(img) return mu def reparameterize(self, mu, logvar): std",
"sample(self, num_samples=64): z = torch.randn(num_samples, 200) samples = self.decoder(z) return",
"kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2,",
"mu**2 - logvar.exp(), dim=1)) loss = recon_loss_factor * recon_loss +",
"= out.view(-1, 64, 8, 8) recon_img = self.deconv_layers(out) return recon_img",
"super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32),",
"logvar.exp(), dim=1)) loss = recon_loss_factor * recon_loss + kld_loss self.log('train/loss',",
"self.encoder(img) recon_img = self.decoder(mu) return recon_img def sample(self, num_samples=64): z",
"nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(),",
"torchvision.datasets import CelebA class Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers =",
"out = out.view(-1, 64, 8, 8) recon_img = self.deconv_layers(out) return",
"as nn import torch.nn.functional as F import torch.optim as optim",
"loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return loss def validation_step(self, val_batch,",
"recon_img def sample(self, num_samples=64): z = torch.randn(num_samples, 200) samples =",
"val_batch, batch_idx): img, labels = val_batch mu, logvar = self.encoder(img)",
"if __name__ == '__main__': # data transform = transforms.Compose([ transforms.RandomHorizontalFlip(),",
"torch.sum(1 + logvar - mu**2 - logvar.exp(), dim=1)) loss =",
"self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return loss def validation_step(self, val_batch, batch_idx):",
"def forward(self, imgs): out = self.conv_layers(imgs) out = nn.Flatten()(out) mu",
"nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64,",
"labels = val_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu,",
"logvar class Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input = nn.Linear(200, 4096)",
"= optim.Adam(self.parameters(), lr=0.005) return optimizer def training_step(self, train_batch, batch_idx): img,",
"loss def validation_step(self, val_batch, batch_idx): img, labels = val_batch mu,",
"optimizer = optim.Adam(self.parameters(), lr=0.005) return optimizer def training_step(self, train_batch, batch_idx):",
"padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(),",
"def reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar) eps",
"imgs): out = self.conv_layers(imgs) out = nn.Flatten()(out) mu = self.mu_layer(out)",
"# training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0],",
"recon_img = self.decoder(mu) return recon_img def sample(self, num_samples=64): z =",
"nn.Linear(200, 4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1,",
"def training_step(self, train_batch, batch_idx): img, labels = train_batch mu, logvar",
"nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64,",
"padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1),",
"out = nn.Flatten()(out) mu = self.mu_layer(out) logvar = self.logvar_layer(out) return",
"= nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(),",
"kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2,",
"def __init__(self): super().__init__() self.decoder_input = nn.Linear(200, 4096) self.deconv_layers = nn.Sequential(",
"kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return loss def",
"import pytorch_lightning as pl import torch import torch.nn as nn",
"+ mu def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005) return optimizer",
"Encoder() self.decoder = Decoder() def forward(self, img): mu, logvar =",
"logvar = self.encoder(img) z = self.reparameterize(mu, logvar) recon_img = self.decoder(z)",
"torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets import",
"eps * std + mu def configure_optimizers(self): optimizer = optim.Adam(self.parameters(),",
"import torch import torch.nn as nn import torch.nn.functional as F",
"dim=1)) loss = recon_loss_factor * recon_loss + kld_loss self.log('train/loss', loss)",
"padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1),",
"forward(self, imgs): out = self.conv_layers(imgs) out = nn.Flatten()(out) mu =",
"out = self.decoder_input(z) out = out.view(-1, 64, 8, 8) recon_img",
"batch_idx): img, labels = train_batch mu, logvar = self.encoder(img) z",
"nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer",
"= nn.Flatten()(out) mu = self.mu_layer(out) logvar = self.logvar_layer(out) return mu,",
"from torchvision.datasets import CelebA class Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers",
"import TensorBoardLogger from torch.utils.data import DataLoader from torchvision import transforms",
"10000 recon_loss = F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5 * torch.sum(1",
"val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model model",
"padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self, z): out =",
"__init__(self): super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1),",
"self.encoder(img) return mu def reparameterize(self, mu, logvar): std = torch.exp(0.5",
"def sample(self, num_samples=64): z = torch.randn(num_samples, 200) samples = self.decoder(z)",
"stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64),",
"nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64,",
"nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(),",
"import torch.nn as nn import torch.nn.functional as F import torch.optim",
"4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1),",
"mu, logvar = self.encoder(img) return mu def reparameterize(self, mu, logvar):",
"self.logvar_layer = nn.Linear(4096, 200) def forward(self, imgs): out = self.conv_layers(imgs)",
"= nn.Linear(4096, 200) def forward(self, imgs): out = self.conv_layers(imgs) out",
"= self.decoder_input(z) out = out.view(-1, 64, 8, 8) recon_img =",
"32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2,",
"class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder = Encoder() self.decoder =",
") def forward(self, z): out = self.decoder_input(z) out = out.view(-1,",
"self.conv_layers = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(),",
"torchvision import transforms from torchvision.datasets import CelebA class Encoder(nn.Module): def",
"batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False,",
"self.decoder(mu) return recon_img def sample(self, num_samples=64): z = torch.randn(num_samples, 200)",
"= val_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu, logvar)",
"= self.decoder(z) recon_loss_factor = 10000 recon_loss = F.mse_loss(recon_img, img) kld_loss",
"]) train_dataset = CelebA(root='data', split='train', transform=transform, download=False) val_dataset = CelebA(root='data',",
"VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder = Encoder() self.decoder = Decoder()",
"kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096, 200)",
"stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1,",
"self.decoder = Decoder() def forward(self, img): mu, logvar = self.encoder(img)",
"return mu def reparameterize(self, mu, logvar): std = torch.exp(0.5 *",
"z = self.reparameterize(mu, logvar) recon_img = self.decoder(z) recon_loss_factor = 10000",
"stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096, 200) self.logvar_layer",
"training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200,",
"64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2,",
"loss = recon_loss_factor * recon_loss + kld_loss self.log('val/loss', loss) self.log('val/recon_loss',",
"self.decoder(z) recon_loss_factor = 10000 recon_loss = F.mse_loss(recon_img, img) kld_loss =",
"nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3,",
"return eps * std + mu def configure_optimizers(self): optimizer =",
"200) def forward(self, imgs): out = self.conv_layers(imgs) out = nn.Flatten()(out)",
"return mu, logvar class Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input =",
"kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar - mu**2 -",
"= train_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu, logvar)",
"nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3,",
"recon_loss_factor = 10000 recon_loss = F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5",
"transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train', transform=transform, download=False) val_dataset =",
"optim.Adam(self.parameters(), lr=0.005) return optimizer def training_step(self, train_batch, batch_idx): img, labels",
"Decoder() def forward(self, img): mu, logvar = self.encoder(img) return mu",
"self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64),",
"return optimizer def training_step(self, train_batch, batch_idx): img, labels = train_batch",
"std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return eps",
"padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096, 200) self.logvar_layer =",
"train_batch, batch_idx): img, labels = train_batch mu, logvar = self.encoder(img)",
"= recon_loss_factor * recon_loss + kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss)",
"lr=0.005) return optimizer def training_step(self, train_batch, batch_idx): img, labels =",
"= torch.exp(0.5 * logvar) eps = torch.randn_like(std) return eps *",
"self.mu_layer = nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096, 200) def forward(self,",
"mu, logvar = self.encoder(img) z = self.reparameterize(mu, logvar) recon_img =",
"self.encoder = Encoder() self.decoder = Decoder() def forward(self, img): mu,",
"nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64,",
"def forward(self, z): out = self.decoder_input(z) out = out.view(-1, 64,",
"from torch.utils.data import DataLoader from torchvision import transforms from torchvision.datasets",
"200) samples = self.decoder(z) return samples if __name__ == '__main__':",
"img): mu, _ = self.encoder(img) recon_img = self.decoder(mu) return recon_img",
"tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200, logger=tb_logger)",
"super().__init__() self.decoder_input = nn.Linear(200, 4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64,",
"recon_loss) self.log('train/kl_loss', kld_loss) return loss def validation_step(self, val_batch, batch_idx): img,",
"self.log('val/kl_loss', kld_loss) return loss def reconstruct(self, img): mu, _ =",
"nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64,",
"DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model model = VanillaVAE()",
"mu, logvar class Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input = nn.Linear(200,",
"200) self.logvar_layer = nn.Linear(4096, 200) def forward(self, imgs): out =",
"nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), )",
"# model model = VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs',",
"val_dataset = CelebA(root='data', split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32,",
"self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder =",
"std + mu def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005) return",
"transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train', transform=transform, download=False)",
"return loss def reconstruct(self, img): mu, _ = self.encoder(img) recon_img",
"optimizer def training_step(self, train_batch, batch_idx): img, labels = train_batch mu,",
"= torch.randn(num_samples, 200) samples = self.decoder(z) return samples if __name__",
"= CelebA(root='data', split='train', transform=transform, download=False) val_dataset = CelebA(root='data', split='test', transform=transform,",
"pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from torchvision import",
"img) kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar - mu**2",
"train_dataset = CelebA(root='data', split='train', transform=transform, download=False) val_dataset = CelebA(root='data', split='test',",
"TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200, logger=tb_logger) trainer.fit(model, train_loader,",
"64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3,",
"download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader =",
"DataLoader from torchvision import transforms from torchvision.datasets import CelebA class",
") self.mu_layer = nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096, 200) def",
"train_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu, logvar) recon_img",
"self.conv_layers(imgs) out = nn.Flatten()(out) mu = self.mu_layer(out) logvar = self.logvar_layer(out)",
"nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64,",
"download=False) val_dataset = CelebA(root='data', split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset,",
"shuffle=False, drop_last=True) # model model = VanillaVAE() # training tb_logger",
"kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self, z):",
"out = self.conv_layers(imgs) out = nn.Flatten()(out) mu = self.mu_layer(out) logvar",
"mu def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005) return optimizer def",
"mu def reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar)",
"3, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self,",
"self.decoder_input = nn.Linear(200, 4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3,",
"eps = torch.randn_like(std) return eps * std + mu def",
"transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train',",
"torch.mean(-0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp(), dim=1))",
"= recon_loss_factor * recon_loss + kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss)",
"= self.mu_layer(out) logvar = self.logvar_layer(out) return mu, logvar class Decoder(nn.Module):",
"labels = train_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu,",
"kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2,",
"recon_img = self.decoder(z) recon_loss_factor = 10000 recon_loss = F.mse_loss(recon_img, img)",
"recon_loss + kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return",
"__name__ == '__main__': # data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148),",
"torch.optim as optim from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import",
"* recon_loss + kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss)",
"_ = self.encoder(img) recon_img = self.decoder(mu) return recon_img def sample(self,",
"nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(),",
"z): out = self.decoder_input(z) out = out.view(-1, 64, 8, 8)",
"Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input = nn.Linear(200, 4096) self.deconv_layers =",
"nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3,",
"= self.reparameterize(mu, logvar) recon_img = self.decoder(z) recon_loss_factor = 10000 recon_loss",
"transform=transform, download=False) val_dataset = CelebA(root='data', split='test', transform=transform, download=False) train_loader =",
"train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset,",
"self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return loss def reconstruct(self, img): mu,",
"pl import torch import torch.nn as nn import torch.nn.functional as",
"stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64),",
"= nn.Linear(200, 4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2,",
"transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset =",
"= self.encoder(img) recon_img = self.decoder(mu) return recon_img def sample(self, num_samples=64):",
"pytorch_lightning as pl import torch import torch.nn as nn import",
"nn.Sequential( nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64,",
"shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) #",
"* std + mu def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005)",
"transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train', transform=transform,",
"+ kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return loss",
"mu = self.mu_layer(out) logvar = self.logvar_layer(out) return mu, logvar class",
"torch.nn.functional as F import torch.optim as optim from pytorch_lightning.loggers import",
"self.mu_layer(out) logvar = self.logvar_layer(out) return mu, logvar class Decoder(nn.Module): def",
"= self.decoder(mu) return recon_img def sample(self, num_samples=64): z = torch.randn(num_samples,",
"drop_last=True) # model model = VanillaVAE() # training tb_logger =",
"def reconstruct(self, img): mu, _ = self.encoder(img) recon_img = self.decoder(mu)",
"== '__main__': # data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128),",
"= self.logvar_layer(out) return mu, logvar class Decoder(nn.Module): def __init__(self): super().__init__()",
"kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return loss def",
"64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3,",
"validation_step(self, val_batch, batch_idx): img, labels = val_batch mu, logvar =",
"batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model model = VanillaVAE() #",
"as F import torch.optim as optim from pytorch_lightning.loggers import TensorBoardLogger",
"torch.nn as nn import torch.nn.functional as F import torch.optim as",
"stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1,",
"logvar) recon_img = self.decoder(z) recon_loss_factor = 10000 recon_loss = F.mse_loss(recon_img,",
"def forward(self, img): mu, logvar = self.encoder(img) return mu def",
"'__main__': # data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor()",
"- logvar.exp(), dim=1)) loss = recon_loss_factor * recon_loss + kld_loss",
"TensorBoardLogger from torch.utils.data import DataLoader from torchvision import transforms from",
"= self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder",
"recon_loss + kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return",
"= TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200, logger=tb_logger) trainer.fit(model,",
"self.decoder_input(z) out = out.view(-1, 64, 8, 8) recon_img = self.deconv_layers(out)",
"reparameterize(self, mu, logvar): std = torch.exp(0.5 * logvar) eps =",
"name='vanilla_vae_celeba', default_hp_metric=False) trainer = pl.Trainer(gpus=[0], max_epochs=200, logger=tb_logger) trainer.fit(model, train_loader, val_loader)",
"8, 8) recon_img = self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule): def",
"output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64),",
"dim=1)) loss = recon_loss_factor * recon_loss + kld_loss self.log('val/loss', loss)",
"self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return loss def reconstruct(self,",
"mu, _ = self.encoder(img) recon_img = self.decoder(mu) return recon_img def",
"= DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32,",
"as optim from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader",
"import transforms from torchvision.datasets import CelebA class Encoder(nn.Module): def __init__(self):",
"CelebA(root='data', split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True,",
"def configure_optimizers(self): optimizer = optim.Adam(self.parameters(), lr=0.005) return optimizer def training_step(self,",
"self.log('train/kl_loss', kld_loss) return loss def validation_step(self, val_batch, batch_idx): img, labels",
"recon_loss = F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5 * torch.sum(1 +",
"nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096,",
"= torch.randn_like(std) return eps * std + mu def configure_optimizers(self):",
"= nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32,",
"recon_img = self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__()",
"= CelebA(root='data', split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8,",
"optim from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from",
"import CelebA class Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers = nn.Sequential(",
"num_samples=64): z = torch.randn(num_samples, 200) samples = self.decoder(z) return samples",
"output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32),",
"model model = VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba',",
"stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self, z): out",
"split='train', transform=transform, download=False) val_dataset = CelebA(root='data', split='test', transform=transform, download=False) train_loader",
"output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self, z): out = self.decoder_input(z)",
"import torch.optim as optim from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data",
"= nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096, 200) def forward(self, imgs):",
"data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset",
"logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std) return",
"num_workers=8, shuffle=False, drop_last=True) # model model = VanillaVAE() # training",
"nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32,",
"VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer =",
"CelebA(root='data', split='train', transform=transform, download=False) val_dataset = CelebA(root='data', split='test', transform=transform, download=False)",
"nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096, 200) def forward(self, imgs): out",
"self.logvar_layer(out) return mu, logvar class Decoder(nn.Module): def __init__(self): super().__init__() self.decoder_input",
"model = VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False)",
"64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096,",
"transforms from torchvision.datasets import CelebA class Encoder(nn.Module): def __init__(self): super().__init__()",
"32, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3,",
"= self.encoder(img) z = self.reparameterize(mu, logvar) recon_img = self.decoder(z) recon_loss_factor",
"nn.BatchNorm2d(3), nn.Sigmoid(), ) def forward(self, z): out = self.decoder_input(z) out",
"__init__(self): super().__init__() self.encoder = Encoder() self.decoder = Decoder() def forward(self,",
"batch_idx): img, labels = val_batch mu, logvar = self.encoder(img) z",
"__init__(self): super().__init__() self.decoder_input = nn.Linear(200, 4096) self.deconv_layers = nn.Sequential( nn.ConvTranspose2d(64,",
"forward(self, img): mu, logvar = self.encoder(img) return mu def reparameterize(self,",
"torch.randn(num_samples, 200) samples = self.decoder(z) return samples if __name__ ==",
"<reponame>aidiary/generative-models-pytorch import pytorch_lightning as pl import torch import torch.nn as",
"F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar -",
"64, 8, 8) recon_img = self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule):",
"+ logvar - mu**2 - logvar.exp(), dim=1)) loss = recon_loss_factor",
"nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32,",
"self.decoder(z) return samples if __name__ == '__main__': # data transform",
"kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1),",
"self.reparameterize(mu, logvar) recon_img = self.decoder(z) recon_loss_factor = 10000 recon_loss =",
"mu, logvar): std = torch.exp(0.5 * logvar) eps = torch.randn_like(std)",
"def __init__(self): super().__init__() self.encoder = Encoder() self.decoder = Decoder() def",
"recon_loss_factor * recon_loss + kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss',",
"training_step(self, train_batch, batch_idx): img, labels = train_batch mu, logvar =",
"8) recon_img = self.deconv_layers(out) return recon_img class VanillaVAE(pl.LightningModule): def __init__(self):",
"transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data', split='train', transform=transform, download=False) val_dataset",
"split='test', transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True)",
"nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64,",
"self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss) return loss def validation_step(self,",
"kld_loss) return loss def reconstruct(self, img): mu, _ = self.encoder(img)",
"reconstruct(self, img): mu, _ = self.encoder(img) recon_img = self.decoder(mu) return",
"samples if __name__ == '__main__': # data transform = transforms.Compose([",
"torch.exp(0.5 * logvar) eps = torch.randn_like(std) return eps * std",
"= torch.mean(-0.5 * torch.sum(1 + logvar - mu**2 - logvar.exp(),",
"= self.decoder(z) return samples if __name__ == '__main__': # data",
"- mu**2 - logvar.exp(), dim=1)) loss = recon_loss_factor * recon_loss",
"= Encoder() self.decoder = Decoder() def forward(self, img): mu, logvar",
"val_batch mu, logvar = self.encoder(img) z = self.reparameterize(mu, logvar) recon_img",
"recon_loss_factor * recon_loss + kld_loss self.log('val/loss', loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss',",
"transform=transform, download=False) train_loader = DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader",
"nn.Flatten()(out) mu = self.mu_layer(out) logvar = self.logvar_layer(out) return mu, logvar",
"logvar) eps = torch.randn_like(std) return eps * std + mu",
"Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3,",
"= VanillaVAE() # training tb_logger = TensorBoardLogger('lightning_logs', name='vanilla_vae_celeba', default_hp_metric=False) trainer",
"= Decoder() def forward(self, img): mu, logvar = self.encoder(img) return",
"img, labels = val_batch mu, logvar = self.encoder(img) z =",
"F import torch.optim as optim from pytorch_lightning.loggers import TensorBoardLogger from",
"super().__init__() self.encoder = Encoder() self.decoder = Decoder() def forward(self, img):",
"CelebA class Encoder(nn.Module): def __init__(self): super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3,",
"samples = self.decoder(z) return samples if __name__ == '__main__': #",
"self.encoder(img) z = self.reparameterize(mu, logvar) recon_img = self.decoder(z) recon_loss_factor =",
"num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True)",
"= 10000 recon_loss = F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5 *",
"logvar.exp(), dim=1)) loss = recon_loss_factor * recon_loss + kld_loss self.log('val/loss',",
"output_padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3),",
"loss = recon_loss_factor * recon_loss + kld_loss self.log('train/loss', loss) self.log('train/recon_loss',",
"nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), ) def",
"logvar - mu**2 - logvar.exp(), dim=1)) loss = recon_loss_factor *",
"nn.LeakyReLU(), nn.ConvTranspose2d(32, 3, kernel_size=3, stride=2, padding=1, output_padding=1), nn.BatchNorm2d(3), nn.Sigmoid(), )",
"= self.encoder(img) return mu def reparameterize(self, mu, logvar): std =",
"return samples if __name__ == '__main__': # data transform =",
"padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(),",
"# data transform = transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ])",
"logvar = self.logvar_layer(out) return mu, logvar class Decoder(nn.Module): def __init__(self):",
"kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(32), nn.LeakyReLU(), nn.Conv2d(32, 64, kernel_size=3, stride=2, padding=1),",
"* recon_loss + kld_loss self.log('train/loss', loss) self.log('train/recon_loss', recon_loss) self.log('train/kl_loss', kld_loss)",
"torch import torch.nn as nn import torch.nn.functional as F import",
"* torch.sum(1 + logvar - mu**2 - logvar.exp(), dim=1)) loss",
"padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 32, kernel_size=3, stride=2, padding=1, output_padding=1),",
"= DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model model =",
"from pytorch_lightning.loggers import TensorBoardLogger from torch.utils.data import DataLoader from torchvision",
"= F.mse_loss(recon_img, img) kld_loss = torch.mean(-0.5 * torch.sum(1 + logvar",
"def validation_step(self, val_batch, batch_idx): img, labels = val_batch mu, logvar",
"import torch.nn.functional as F import torch.optim as optim from pytorch_lightning.loggers",
"= transforms.Compose([ transforms.RandomHorizontalFlip(), transforms.CenterCrop(148), transforms.Resize(128), transforms.ToTensor() ]) train_dataset = CelebA(root='data',",
"nn.LeakyReLU(), ) self.mu_layer = nn.Linear(4096, 200) self.logvar_layer = nn.Linear(4096, 200)",
"import DataLoader from torchvision import transforms from torchvision.datasets import CelebA",
"DataLoader(train_dataset, batch_size=32, num_workers=8, shuffle=True, drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8,",
"img, labels = train_batch mu, logvar = self.encoder(img) z =",
"kld_loss) return loss def validation_step(self, val_batch, batch_idx): img, labels =",
"stride=2, padding=1, output_padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.ConvTranspose2d(64, 64, kernel_size=3, stride=2, padding=1,",
"torch.randn_like(std) return eps * std + mu def configure_optimizers(self): optimizer",
"loss) self.log('val/recon_loss', recon_loss) self.log('val/kl_loss', kld_loss) return loss def reconstruct(self, img):",
"return recon_img class VanillaVAE(pl.LightningModule): def __init__(self): super().__init__() self.encoder = Encoder()",
"from torchvision import transforms from torchvision.datasets import CelebA class Encoder(nn.Module):",
"loss def reconstruct(self, img): mu, _ = self.encoder(img) recon_img =",
"return loss def validation_step(self, val_batch, batch_idx): img, labels = val_batch",
"drop_last=True) val_loader = DataLoader(val_dataset, batch_size=32, num_workers=8, shuffle=False, drop_last=True) # model",
"img): mu, logvar = self.encoder(img) return mu def reparameterize(self, mu,",
"nn.Conv2d(64, 64, kernel_size=3, stride=2, padding=1), nn.BatchNorm2d(64), nn.LeakyReLU(), nn.Conv2d(64, 64, kernel_size=3,",
"nn import torch.nn.functional as F import torch.optim as optim from",
"def __init__(self): super().__init__() self.conv_layers = nn.Sequential( nn.Conv2d(3, 32, kernel_size=3, stride=2,",
"z = torch.randn(num_samples, 200) samples = self.decoder(z) return samples if",
"as pl import torch import torch.nn as nn import torch.nn.functional",
"forward(self, z): out = self.decoder_input(z) out = out.view(-1, 64, 8,",
"nn.Sigmoid(), ) def forward(self, z): out = self.decoder_input(z) out =",
"recon_loss) self.log('val/kl_loss', kld_loss) return loss def reconstruct(self, img): mu, _",
"* logvar) eps = torch.randn_like(std) return eps * std +"
] |
[
"Cleaned dataframe \"\"\" categories = df['categories'].str.split( pat=';', expand=True) row =",
"argument respectively, as '\\ 'well as the filepath of the",
"database_filename): \"\"\" Saves the DataFrame Parameters: df (DataFrame): Cleaned DataFrame",
"import pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath,",
"df = pd.merge(messages,categories,on='id') return df def clean_data(df): \"\"\" Cleans the",
"filepath of the database to save the cleaned data '\\",
"df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def save_data(df, database_filename):",
"print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df =",
"# Import libraries import sys import pandas as pd from",
"sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): \"\"\" Load the data",
"the SQLite Database \"\"\" engine = create_engine('sqlite:///' + database_filename +",
"category_colnames = row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns = category_colnames for",
"create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') def",
"load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\\n DATABASE:",
"create_engine def load_data(messages_filepath, categories_filepath): \"\"\" Load the data from the",
"= sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath))",
"def load_data(messages_filepath, categories_filepath): \"\"\" Load the data from the disaster",
"clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved",
"(str): Path to messages csv categories_filepath (str): Path to categories",
"pd.merge(messages,categories,on='id') return df def clean_data(df): \"\"\" Cleans the categories Parameters:",
"df.drop(['categories'], axis=1, inplace=True) df = df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True)",
"the disaster response csvs Parameters: messages_filepath (str): Path to messages",
"save_data(df, database_filepath) print('Cleaned data saved to database!') else: print('Please provide",
"'\\ 'well as the filepath of the database to save",
"return df def clean_data(df): \"\"\" Cleans the categories Parameters: df",
"the cleaned data '\\ 'to as the third argument. \\n\\nExample:",
"Parameters: df (DataFrame): Cleaned DataFrame database_filename (DataFrame): Path to the",
"import sys import pandas as pd from sqlalchemy import create_engine",
"for column in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int)",
"respectively, as '\\ 'well as the filepath of the database",
"the DataFrame Parameters: df (DataFrame): Cleaned DataFrame database_filename (DataFrame): Path",
"1 if x > 1 else x) df.drop(['categories'], axis=1, inplace=True)",
"categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda",
"data '\\ 'to as the third argument. \\n\\nExample: python process_data.py",
"DataFrame database_filename (DataFrame): Path to the SQLite Database \"\"\" engine",
"categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}'",
"x > 1 else x) df.drop(['categories'], axis=1, inplace=True) df =",
"sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df",
"row = categories.iloc[[1]] category_colnames = row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns",
"else x) df.drop(['categories'], axis=1, inplace=True) df = df = pd.concat([df,categories],",
"DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!') else:",
"= load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\\n",
"df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): \"\"\" Saves the DataFrame",
"data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!')",
"<reponame>julat/DisasterResponse # Import libraries import sys import pandas as pd",
"saved to database!') else: print('Please provide the filepaths of the",
"categories.columns = category_colnames for column in categories: categories[column] = categories[column].astype(str).str[-1:]",
"\"\"\" Load the data from the disaster response csvs Parameters:",
"the database to save the cleaned data '\\ 'to as",
"if_exists='replace') def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath",
"messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return",
"to messages csv categories_filepath (str): Path to categories csv Returns:",
"CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...')",
"pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df def clean_data(df): \"\"\" Cleans",
"= categories.iloc[[1]] category_colnames = row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns =",
"categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath))",
"database_filepath) print('Cleaned data saved to database!') else: print('Please provide the",
"pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): \"\"\" Load",
"data saved to database!') else: print('Please provide the filepaths of",
"index=False, if_exists='replace') def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath,",
"database to save the cleaned data '\\ 'to as the",
"df.to_sql(database_filename, engine, index=False, if_exists='replace') def main(): if len(sys.argv) == 4:",
"save_data(df, database_filename): \"\"\" Saves the DataFrame Parameters: df (DataFrame): Cleaned",
"main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:]",
"data...') df = clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath)",
"as the third argument. \\n\\nExample: python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv",
"return df def save_data(df, database_filename): \"\"\" Saves the DataFrame Parameters:",
"categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1 if x",
"of the messages and categories '\\ 'datasets as the first",
"cleaned data '\\ 'to as the third argument. \\n\\nExample: python",
"MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath)",
"Cleans the categories Parameters: df (DataFrame): Messy DataFrame Returns: Dataframe:",
"categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda x:",
"def clean_data(df): \"\"\" Cleans the categories Parameters: df (DataFrame): Messy",
"'datasets as the first and second argument respectively, as '\\",
"categories_filepath): \"\"\" Load the data from the disaster response csvs",
"df (DataFrame): Messy DataFrame Returns: Dataframe: Cleaned dataframe \"\"\" categories",
"df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df) print('Saving",
"the categories Parameters: df (DataFrame): Messy DataFrame Returns: Dataframe: Cleaned",
"and categories '\\ 'datasets as the first and second argument",
"{}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to database!') else: print('Please",
"DataFrame Parameters: df (DataFrame): Cleaned DataFrame database_filename (DataFrame): Path to",
"== 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\\n MESSAGES:",
"categories '\\ 'datasets as the first and second argument respectively,",
"'well as the filepath of the database to save the",
"first and second argument respectively, as '\\ 'well as the",
"if x > 1 else x) df.drop(['categories'], axis=1, inplace=True) df",
"print('Please provide the filepaths of the messages and categories '\\",
"df (DataFrame): Cleaned DataFrame database_filename (DataFrame): Path to the SQLite",
"= categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1 if x >",
"Saves the DataFrame Parameters: df (DataFrame): Cleaned DataFrame database_filename (DataFrame):",
"Parameters: messages_filepath (str): Path to messages csv categories_filepath (str): Path",
"x : x.values[0].split(\"-\")[0]) categories.columns = category_colnames for column in categories:",
"x.values[0].split(\"-\")[0]) categories.columns = category_colnames for column in categories: categories[column] =",
"axis=1) df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): \"\"\" Saves the",
"response csvs Parameters: messages_filepath (str): Path to messages csv categories_filepath",
"categories Parameters: df (DataFrame): Messy DataFrame Returns: Dataframe: Cleaned dataframe",
"the first and second argument respectively, as '\\ 'well as",
"inplace=True) df = df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df",
"disaster response csvs Parameters: messages_filepath (str): Path to messages csv",
"print('Cleaning data...') df = clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df,",
"as the first and second argument respectively, as '\\ 'well",
"{}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning",
"\"\"\" messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id')",
"argument. \\n\\nExample: python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db') if",
"column in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column]",
"Path to categories csv Returns: Dataframe: Merged data \"\"\" messages",
"filepaths of the messages and categories '\\ 'datasets as the",
"'to as the third argument. \\n\\nExample: python process_data.py '\\ 'disaster_messages.csv",
"\"\"\" categories = df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]] category_colnames",
"categories.iloc[[1]] category_colnames = row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns = category_colnames",
"to the SQLite Database \"\"\" engine = create_engine('sqlite:///' + database_filename",
"\\n\\nExample: python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db') if __name__",
"sys import pandas as pd from sqlalchemy import create_engine def",
"categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df = clean_data(df)",
"print('Cleaned data saved to database!') else: print('Please provide the filepaths",
"csvs Parameters: messages_filepath (str): Path to messages csv categories_filepath (str):",
"(DataFrame): Path to the SQLite Database \"\"\" engine = create_engine('sqlite:///'",
"categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1 if x > 1",
"(str): Path to categories csv Returns: Dataframe: Merged data \"\"\"",
"messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n CATEGORIES:",
"= df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def save_data(df,",
"categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1 if",
"= categories[column].map(lambda x: 1 if x > 1 else x)",
"+ database_filename + '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') def main():",
"database_filename + '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') def main(): if",
".format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df =",
"pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): \"\"\" Saves",
"engine = create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename, engine, index=False,",
"df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]] category_colnames = row.apply(lambda x",
"'.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') def main(): if len(sys.argv) ==",
"database!') else: print('Please provide the filepaths of the messages and",
"Merged data \"\"\" messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df",
"1 else x) df.drop(['categories'], axis=1, inplace=True) df = df =",
"= pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def save_data(df, database_filename): \"\"\"",
"database_filename (DataFrame): Path to the SQLite Database \"\"\" engine =",
"Path to the SQLite Database \"\"\" engine = create_engine('sqlite:///' +",
"Returns: Dataframe: Merged data \"\"\" messages = pd.read_csv(messages_filepath) categories =",
"pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df def",
"libraries import sys import pandas as pd from sqlalchemy import",
"> 1 else x) df.drop(['categories'], axis=1, inplace=True) df = df",
"Path to messages csv categories_filepath (str): Path to categories csv",
"categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df def clean_data(df):",
"'\\ 'datasets as the first and second argument respectively, as",
"= df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]] category_colnames = row.apply(lambda",
"python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db') if __name__ ==",
"third argument. \\n\\nExample: python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db')",
"pandas as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath):",
"Parameters: df (DataFrame): Messy DataFrame Returns: Dataframe: Cleaned dataframe \"\"\"",
"Messy DataFrame Returns: Dataframe: Cleaned dataframe \"\"\" categories = df['categories'].str.split(",
"import create_engine def load_data(messages_filepath, categories_filepath): \"\"\" Load the data from",
"axis=1, inplace=True) df = df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return",
"and second argument respectively, as '\\ 'well as the filepath",
"from the disaster response csvs Parameters: messages_filepath (str): Path to",
"pat=';', expand=True) row = categories.iloc[[1]] category_colnames = row.apply(lambda x :",
"df = df = pd.concat([df,categories], axis=1) df.drop_duplicates(inplace=True) return df def",
"= pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df def clean_data(df): \"\"\"",
"\"\"\" Saves the DataFrame Parameters: df (DataFrame): Cleaned DataFrame database_filename",
"engine, index=False, if_exists='replace') def main(): if len(sys.argv) == 4: messages_filepath,",
"= category_colnames for column in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column]",
"in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] =",
"= create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace')",
"Cleaned DataFrame database_filename (DataFrame): Path to the SQLite Database \"\"\"",
"as pd from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): \"\"\"",
"df = clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned",
"expand=True) row = categories.iloc[[1]] category_colnames = row.apply(lambda x : x.values[0].split(\"-\")[0])",
"df def save_data(df, database_filename): \"\"\" Saves the DataFrame Parameters: df",
"def save_data(df, database_filename): \"\"\" Saves the DataFrame Parameters: df (DataFrame):",
"csv Returns: Dataframe: Merged data \"\"\" messages = pd.read_csv(messages_filepath) categories",
": x.values[0].split(\"-\")[0]) categories.columns = category_colnames for column in categories: categories[column]",
"= categories[column].astype(str).str[-1:] categories[column] = categories[column].astype(int) categories[column] = categories[column].map(lambda x: 1",
"else: print('Please provide the filepaths of the messages and categories",
"= pd.merge(messages,categories,on='id') return df def clean_data(df): \"\"\" Cleans the categories",
"Import libraries import sys import pandas as pd from sqlalchemy",
"\"\"\" Cleans the categories Parameters: df (DataFrame): Messy DataFrame Returns:",
"data from the disaster response csvs Parameters: messages_filepath (str): Path",
"categories csv Returns: Dataframe: Merged data \"\"\" messages = pd.read_csv(messages_filepath)",
"process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db') if __name__ == '__main__':",
"categories = df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]] category_colnames =",
"clean_data(df): \"\"\" Cleans the categories Parameters: df (DataFrame): Messy DataFrame",
"to database!') else: print('Please provide the filepaths of the messages",
"the filepaths of the messages and categories '\\ 'datasets as",
"x: 1 if x > 1 else x) df.drop(['categories'], axis=1,",
"x) df.drop(['categories'], axis=1, inplace=True) df = df = pd.concat([df,categories], axis=1)",
"{}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath, categories_filepath) print('Cleaning data...') df",
"Dataframe: Merged data \"\"\" messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath)",
"categories[column] = categories[column].map(lambda x: 1 if x > 1 else",
"csv categories_filepath (str): Path to categories csv Returns: Dataframe: Merged",
"provide the filepaths of the messages and categories '\\ 'datasets",
"(DataFrame): Cleaned DataFrame database_filename (DataFrame): Path to the SQLite Database",
"def main(): if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath =",
"the filepath of the database to save the cleaned data",
"Returns: Dataframe: Cleaned dataframe \"\"\" categories = df['categories'].str.split( pat=';', expand=True)",
"print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data saved to",
"if len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading",
"= clean_data(df) print('Saving data...\\n DATABASE: {}'.format(database_filepath)) save_data(df, database_filepath) print('Cleaned data",
"+ '.db') df.to_sql(database_filename, engine, index=False, if_exists='replace') def main(): if len(sys.argv)",
"from sqlalchemy import create_engine def load_data(messages_filepath, categories_filepath): \"\"\" Load the",
"row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns = category_colnames for column in",
"data \"\"\" messages = pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df =",
"Dataframe: Cleaned dataframe \"\"\" categories = df['categories'].str.split( pat=';', expand=True) row",
"len(sys.argv) == 4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\\n",
"categories_filepath (str): Path to categories csv Returns: Dataframe: Merged data",
"of the database to save the cleaned data '\\ 'to",
"to categories csv Returns: Dataframe: Merged data \"\"\" messages =",
"(DataFrame): Messy DataFrame Returns: Dataframe: Cleaned dataframe \"\"\" categories =",
"SQLite Database \"\"\" engine = create_engine('sqlite:///' + database_filename + '.db')",
"dataframe \"\"\" categories = df['categories'].str.split( pat=';', expand=True) row = categories.iloc[[1]]",
"messages_filepath (str): Path to messages csv categories_filepath (str): Path to",
"4: messages_filepath, categories_filepath, database_filepath = sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n",
"load_data(messages_filepath, categories_filepath): \"\"\" Load the data from the disaster response",
"the data from the disaster response csvs Parameters: messages_filepath (str):",
"= pd.read_csv(messages_filepath) categories = pd.read_csv(categories_filepath) df = pd.merge(messages,categories,on='id') return df",
"= row.apply(lambda x : x.values[0].split(\"-\")[0]) categories.columns = category_colnames for column",
"messages and categories '\\ 'datasets as the first and second",
"messages csv categories_filepath (str): Path to categories csv Returns: Dataframe:",
"as the filepath of the database to save the cleaned",
"'\\ 'to as the third argument. \\n\\nExample: python process_data.py '\\",
"database_filepath = sys.argv[1:] print('Loading data...\\n MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath,",
"Load the data from the disaster response csvs Parameters: messages_filepath",
"categories[column].map(lambda x: 1 if x > 1 else x) df.drop(['categories'],",
"data...\\n MESSAGES: {}\\n CATEGORIES: {}' .format(messages_filepath, categories_filepath)) df = load_data(messages_filepath,",
"the third argument. \\n\\nExample: python process_data.py '\\ 'disaster_messages.csv disaster_categories.csv '\\",
"second argument respectively, as '\\ 'well as the filepath of",
"df def clean_data(df): \"\"\" Cleans the categories Parameters: df (DataFrame):",
"as '\\ 'well as the filepath of the database to",
"category_colnames for column in categories: categories[column] = categories[column].astype(str).str[-1:] categories[column] =",
"'\\ 'disaster_messages.csv disaster_categories.csv '\\ 'DisasterResponse.db') if __name__ == '__main__': main()",
"save the cleaned data '\\ 'to as the third argument.",
"\"\"\" engine = create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename, engine,",
"to save the cleaned data '\\ 'to as the third",
"DataFrame Returns: Dataframe: Cleaned dataframe \"\"\" categories = df['categories'].str.split( pat=';',",
"the messages and categories '\\ 'datasets as the first and",
"Database \"\"\" engine = create_engine('sqlite:///' + database_filename + '.db') df.to_sql(database_filename,"
] |
[
"], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [",
"in statuses[group] if srv in stat) if status not in",
"; sudo -E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as err: message",
"1912: statuses = get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services) for group",
"'job', ], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ],",
"('CRITICAL: Could not get contrail-status.' ' return code: {} cmd:",
"contrail-status.' ' return code: {} cmd: {} output: {}'. format(err.returncode,",
"in str(cver): if cver == '5.0': version = 500 elif",
"if '.' in str(cver): if cver == '5.0': version =",
"4 and words[0] == '==' and words[3] == '==': group",
"the contrail-status' .format(srv)) print(message) sys.exit(WARNING) status = next(stat[srv] for stat",
"OK') sys.exit() if __name__ == '__main__': cver = sys.argv[1] if",
"err.output)) print(message) sys.exit(CRITICAL) statuses = output[\"pods\"] return statuses def check_contrail_status(services,",
"return code: {} cmd: {} output: {}'. format(err.returncode, err.cmd, err.output))",
"statuses def get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo",
"'rabbitmq', 'cassandra', ], 'webui': [ 'web', 'job', ], 'config': [",
"line in output.splitlines()[1:]: words = line.split() if len(words) == 4",
"else: print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL:",
"sys.exit(CRITICAL) print('Contrail status OK') sys.exit() if __name__ == '__main__': cver",
"output.splitlines()[1:]: words = line.split() if len(words) == 4 and words[0]",
"words[0] == '==' and words[3] == '==': group = words[2]",
"next(stat[srv] for stat in statuses[group] if srv in stat) if",
"version=None): if version > 1912: statuses = get_contrail_status_json(services) else: statuses",
"{}' .format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail status OK') sys.exit() if",
"import sys import json SERVICES = { 'control': [ 'control',",
"0: group = None continue if group and len(words) >=",
"{} is absent in the contrail-status' .format(srv)) print(message) sys.exit(WARNING) status",
"def get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E",
"= 500 elif cver == '5.1': version = 510 else:",
"version: {}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver))",
"'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ], } WARNING = 1",
"2 and group in services: srv = words[0].split(':')[0] statuses.setdefault(group, list()).append(",
"not cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) else: version =",
"continue if group and len(words) >= 2 and group in",
"'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ], } WARNING",
"2 def get_contrail_status_txt(services): try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo",
"group = None continue if group and len(words) >= 2",
"Could not get contrail-status.' ' return code: {} cmd: {}",
"in services: srv = words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])})",
"srv in stat) if status not in ['active', 'backup']: message",
"{} is absent in the contrail-status' .format(group)) print(message) sys.exit(WARNING) for",
"sys.exit() if __name__ == '__main__': cver = sys.argv[1] if '.'",
"statuses = get_contrail_status_txt(services) for group in services: if group not",
"{ 'control': [ 'control', 'nodemgr', 'named', 'dns', ], 'config-database': [",
"except subprocess.CalledProcessError as err: message = ('CRITICAL: Could not get",
"{srv: ' '.join(words[1:])}) return statuses def get_contrail_status_json(services): try: output =",
".format(group)) print(message) sys.exit(WARNING) for srv in services[group]: if not any(srv",
"sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) else:",
"for srv in services[group]: if not any(srv in key for",
"sudo -E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as err: message =",
"output: {}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = dict()",
"cver == '5.0': version = 500 elif cver == '5.1':",
"cmd: {} output: {}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses",
"version = 500 elif cver == '5.1': version = 510",
">= 2 and group in services: srv = words[0].split(':')[0] statuses.setdefault(group,",
"statuses = dict() group = None for line in output.splitlines()[1:]:",
"None for line in output.splitlines()[1:]: words = line.split() if len(words)",
"statuses def check_contrail_status(services, version=None): if version > 1912: statuses =",
"print(message) sys.exit(CRITICAL) statuses = dict() group = None for line",
"invalid version: {}\".format(cver)) sys.exit(CRITICAL) else: version = int(cver) check_contrail_status(SERVICES, version=version)",
"is absent in the contrail-status' .format(group)) print(message) sys.exit(WARNING) for srv",
"as err: message = ('CRITICAL: Could not get contrail-status.' '",
"print(message) sys.exit(WARNING) for srv in services[group]: if not any(srv in",
"get_contrail_status_txt(services): try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\",",
"== 4 and words[0] == '==' and words[3] == '==':",
"sys.exit(WARNING) status = next(stat[srv] for stat in statuses[group] if srv",
"key in statuses[group]): message = ('WARNING: {} is absent in",
"subprocess import sys import json SERVICES = { 'control': [",
"], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ], }",
"'__main__': cver = sys.argv[1] if '.' in str(cver): if cver",
"if status not in ['active', 'backup']: message = ('CRITICAL: {}",
"500 elif cver == '5.1': version = 510 else: print(\"CRITICAL:",
"ready. Reason: {}' .format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail status OK')",
"sys.argv[1] if '.' in str(cver): if cver == '5.0': version",
"line.split() if len(words) == 4 and words[0] == '==' and",
"('WARNING: POD {} is absent in the contrail-status' .format(group)) print(message)",
"' '.join(words[1:])}) return statuses def get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export",
"elif not cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) else: version",
"= get_contrail_status_txt(services) for group in services: if group not in",
"contrail-status' .format(group)) print(message) sys.exit(WARNING) for srv in services[group]: if not",
"group in services: if group not in statuses: message =",
"'webui': [ 'web', 'job', ], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager',",
"= subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError",
"words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])}) return statuses def get_contrail_status_json(services):",
"cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) else: version = int(cver)",
"{} output: {}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses =",
"get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status",
"('WARNING: {} is absent in the contrail-status' .format(srv)) print(message) sys.exit(WARNING)",
"contrail-status' .format(srv)) print(message) sys.exit(WARNING) status = next(stat[srv] for stat in",
"message = ('CRITICAL: {} is not ready. Reason: {}' .format(srv,",
"services: if group not in statuses: message = ('WARNING: POD",
"version > 1912: statuses = get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services)",
"for group in services: if group not in statuses: message",
"status OK') sys.exit() if __name__ == '__main__': cver = sys.argv[1]",
"services[group]: if not any(srv in key for key in statuses[group]):",
"if srv in stat) if status not in ['active', 'backup']:",
"#!/usr/bin/env python3 import subprocess import sys import json SERVICES =",
"= sys.argv[1] if '.' in str(cver): if cver == '5.0':",
"not any(srv in key for key in statuses[group]): message =",
"SERVICES = { 'control': [ 'control', 'nodemgr', 'named', 'dns', ],",
"not in ['active', 'backup']: message = ('CRITICAL: {} is not",
"__name__ == '__main__': cver = sys.argv[1] if '.' in str(cver):",
"= line.split() if len(words) == 4 and words[0] == '=='",
"absent in the contrail-status' .format(srv)) print(message) sys.exit(WARNING) status = next(stat[srv]",
"json SERVICES = { 'control': [ 'control', 'nodemgr', 'named', 'dns',",
"> 1912: statuses = get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services) for",
"= json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status --format json\", shell=True).decode('UTF-8'))",
"cver == '5.1': version = 510 else: print(\"CRITICAL: invalid version:",
"} WARNING = 1 CRITICAL = 2 def get_contrail_status_txt(services): try:",
".format(srv)) print(message) sys.exit(WARNING) status = next(stat[srv] for stat in statuses[group]",
"'5.1': version = 510 else: print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL)",
"], } WARNING = 1 CRITICAL = 2 def get_contrail_status_txt(services):",
"== '==': group = words[2] continue if len(words) == 0:",
"{} is not ready. Reason: {}' .format(srv, status)) print(message) sys.exit(CRITICAL)",
"'schema', ], } WARNING = 1 CRITICAL = 2 def",
"def get_contrail_status_txt(services): try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E",
"= 2 def get_contrail_status_txt(services): try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ;",
"'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [ 'web', 'job', ],",
"len(words) >= 2 and group in services: srv = words[0].split(':')[0]",
"in services[group]: if not any(srv in key for key in",
"not get contrail-status.' ' return code: {} cmd: {} output:",
"'.join(words[1:])}) return statuses def get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe",
"if version > 1912: statuses = get_contrail_status_json(services) else: statuses =",
"'named', 'dns', ], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ],",
"1 CRITICAL = 2 def get_contrail_status_txt(services): try: output = subprocess.check_output(\"export",
"sys.exit(CRITICAL) statuses = output[\"pods\"] return statuses def check_contrail_status(services, version=None): if",
"services: srv = words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])}) return",
"== '5.0': version = 500 elif cver == '5.1': version",
"group not in statuses: message = ('WARNING: POD {} is",
"Reason: {}' .format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail status OK') sys.exit()",
"format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = dict() group =",
"= ('WARNING: POD {} is absent in the contrail-status' .format(group))",
"print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL: invalid",
"= words[2] continue if len(words) == 0: group = None",
"if group and len(words) >= 2 and group in services:",
"get_contrail_status_txt(services) for group in services: if group not in statuses:",
"format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = output[\"pods\"] return statuses",
"-E contrail-status --format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err: message",
"= words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])}) return statuses def",
"'nodemgr', 'named', 'dns', ], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra',",
"output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\", shell=True).decode('UTF-8') except",
"stat in statuses[group] if srv in stat) if status not",
"and group in services: srv = words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv:",
"for stat in statuses[group] if srv in stat) if status",
"sys import json SERVICES = { 'control': [ 'control', 'nodemgr',",
"contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as err: message = ('CRITICAL: Could",
"None continue if group and len(words) >= 2 and group",
"in services: if group not in statuses: message = ('WARNING:",
"510 else: print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit():",
"try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\", shell=True).decode('UTF-8')",
"words = line.split() if len(words) == 4 and words[0] ==",
"in stat) if status not in ['active', 'backup']: message =",
"' return code: {} cmd: {} output: {}'. format(err.returncode, err.cmd,",
".format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail status OK') sys.exit() if __name__",
"'5.0': version = 500 elif cver == '5.1': version =",
"POD {} is absent in the contrail-status' .format(group)) print(message) sys.exit(WARNING)",
"in ['active', 'backup']: message = ('CRITICAL: {} is not ready.",
"'cassandra', ], 'webui': [ 'web', 'job', ], 'config': [ 'svc-monitor',",
"contrail-status --format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err: message =",
"return statuses def check_contrail_status(services, version=None): if version > 1912: statuses",
"'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [ 'web',",
"CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status --format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError",
"{}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = output[\"pods\"] return",
"subprocess.CalledProcessError as err: message = ('CRITICAL: Could not get contrail-status.'",
"output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status --format json\",",
"['active', 'backup']: message = ('CRITICAL: {} is not ready. Reason:",
"'dns', ], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui':",
"if not any(srv in key for key in statuses[group]): message",
"not ready. Reason: {}' .format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail status",
"subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as",
"elif cver == '5.1': version = 510 else: print(\"CRITICAL: invalid",
"dict() group = None for line in output.splitlines()[1:]: words =",
"python3 import subprocess import sys import json SERVICES = {",
"any(srv in key for key in statuses[group]): message = ('WARNING:",
"'==' and words[3] == '==': group = words[2] continue if",
"for key in statuses[group]): message = ('WARNING: {} is absent",
"output[\"pods\"] return statuses def check_contrail_status(services, version=None): if version > 1912:",
"if __name__ == '__main__': cver = sys.argv[1] if '.' in",
"-E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as err: message = ('CRITICAL:",
"'backup']: message = ('CRITICAL: {} is not ready. Reason: {}'",
"statuses = output[\"pods\"] return statuses def check_contrail_status(services, version=None): if version",
"str(cver): if cver == '5.0': version = 500 elif cver",
"= None for line in output.splitlines()[1:]: words = line.split() if",
"= ('CRITICAL: {} is not ready. Reason: {}' .format(srv, status))",
"status)) print(message) sys.exit(CRITICAL) print('Contrail status OK') sys.exit() if __name__ ==",
"group = None for line in output.splitlines()[1:]: words = line.split()",
"err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = dict() group = None",
"statuses = get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services) for group in",
"print(message) sys.exit(WARNING) status = next(stat[srv] for stat in statuses[group] if",
"'control': [ 'control', 'nodemgr', 'named', 'dns', ], 'config-database': [ 'nodemgr',",
"srv in services[group]: if not any(srv in key for key",
"message = ('WARNING: {} is absent in the contrail-status' .format(srv))",
"message = ('CRITICAL: Could not get contrail-status.' ' return code:",
"= { 'control': [ 'control', 'nodemgr', 'named', 'dns', ], 'config-database':",
"err.output)) print(message) sys.exit(CRITICAL) statuses = dict() group = None for",
"else: statuses = get_contrail_status_txt(services) for group in services: if group",
"return statuses def get_contrail_status_json(services): try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ;",
"status = next(stat[srv] for stat in statuses[group] if srv in",
"= next(stat[srv] for stat in statuses[group] if srv in stat)",
"shell=True).decode('UTF-8') except subprocess.CalledProcessError as err: message = ('CRITICAL: Could not",
"sys.exit(WARNING) for srv in services[group]: if not any(srv in key",
"== '5.1': version = 510 else: print(\"CRITICAL: invalid version: {}\".format(cver))",
"== '__main__': cver = sys.argv[1] if '.' in str(cver): if",
"= dict() group = None for line in output.splitlines()[1:]: words",
"and words[0] == '==' and words[3] == '==': group =",
"statuses[group] if srv in stat) if status not in ['active',",
"= 510 else: print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif not",
"= output[\"pods\"] return statuses def check_contrail_status(services, version=None): if version >",
"[ 'web', 'job', ], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api',",
"code: {} cmd: {} output: {}'. format(err.returncode, err.cmd, err.output)) print(message)",
"; sudo -E contrail-status --format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as",
"get contrail-status.' ' return code: {} cmd: {} output: {}'.",
"json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status --format json\", shell=True).decode('UTF-8')) except",
"if len(words) == 4 and words[0] == '==' and words[3]",
"statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])}) return statuses def get_contrail_status_json(services): try:",
"continue if len(words) == 0: group = None continue if",
"srv = words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: ' '.join(words[1:])}) return statuses",
"if len(words) == 0: group = None continue if group",
"'nodemgr', 'device-manager', 'api', 'schema', ], } WARNING = 1 CRITICAL",
"= ('CRITICAL: Could not get contrail-status.' ' return code: {}",
"{}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL)",
"group = words[2] continue if len(words) == 0: group =",
"get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services) for group in services: if",
"CRITICAL = 2 def get_contrail_status_txt(services): try: output = subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe",
"group and len(words) >= 2 and group in services: srv",
"print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) else: version = int(cver) check_contrail_status(SERVICES,",
"import subprocess import sys import json SERVICES = { 'control':",
"], 'webui': [ 'web', 'job', ], 'config': [ 'svc-monitor', 'nodemgr',",
"for line in output.splitlines()[1:]: words = line.split() if len(words) ==",
"try: output = json.loads(subprocess.check_output(\"export CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status --format",
"if cver == '5.0': version = 500 elif cver ==",
"statuses[group]): message = ('WARNING: {} is absent in the contrail-status'",
"message = ('WARNING: POD {} is absent in the contrail-status'",
"in key for key in statuses[group]): message = ('WARNING: {}",
"import json SERVICES = { 'control': [ 'control', 'nodemgr', 'named',",
"'device-manager', 'api', 'schema', ], } WARNING = 1 CRITICAL =",
"--format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err: message = ('CRITICAL:",
"{} cmd: {} output: {}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL)",
"= ('WARNING: {} is absent in the contrail-status' .format(srv)) print(message)",
"err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = output[\"pods\"] return statuses def",
"'web', 'job', ], 'config': [ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema',",
"group in services: srv = words[0].split(':')[0] statuses.setdefault(group, list()).append( {srv: '",
"stat) if status not in ['active', 'backup']: message = ('CRITICAL:",
"in statuses[group]): message = ('WARNING: {} is absent in the",
"if group not in statuses: message = ('WARNING: POD {}",
"output: {}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = output[\"pods\"]",
"is absent in the contrail-status' .format(srv)) print(message) sys.exit(WARNING) status =",
"CONTRAIL_STATUS_CONTAINER_NAME=contrail-status-controller-nrpe ; sudo -E contrail-status\", shell=True).decode('UTF-8') except subprocess.CalledProcessError as err:",
"statuses: message = ('WARNING: POD {} is absent in the",
"[ 'control', 'nodemgr', 'named', 'dns', ], 'config-database': [ 'nodemgr', 'zookeeper',",
"invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif not cver.isdigit(): print(\"CRITICAL: invalid version:",
"err: message = ('CRITICAL: Could not get contrail-status.' ' return",
"the contrail-status' .format(group)) print(message) sys.exit(WARNING) for srv in services[group]: if",
"and words[3] == '==': group = words[2] continue if len(words)",
"print(message) sys.exit(CRITICAL) statuses = output[\"pods\"] return statuses def check_contrail_status(services, version=None):",
"version = 510 else: print(\"CRITICAL: invalid version: {}\".format(cver)) sys.exit(CRITICAL) elif",
"words[2] continue if len(words) == 0: group = None continue",
"in output.splitlines()[1:]: words = line.split() if len(words) == 4 and",
"key for key in statuses[group]): message = ('WARNING: {} is",
"= 1 CRITICAL = 2 def get_contrail_status_txt(services): try: output =",
"words[3] == '==': group = words[2] continue if len(words) ==",
"is not ready. Reason: {}' .format(srv, status)) print(message) sys.exit(CRITICAL) print('Contrail",
"check_contrail_status(services, version=None): if version > 1912: statuses = get_contrail_status_json(services) else:",
"in the contrail-status' .format(group)) print(message) sys.exit(WARNING) for srv in services[group]:",
"print('Contrail status OK') sys.exit() if __name__ == '__main__': cver =",
"cver = sys.argv[1] if '.' in str(cver): if cver ==",
"== '==' and words[3] == '==': group = words[2] continue",
"= None continue if group and len(words) >= 2 and",
"'.' in str(cver): if cver == '5.0': version = 500",
"not in statuses: message = ('WARNING: POD {} is absent",
"sys.exit(CRITICAL) statuses = dict() group = None for line in",
"[ 'nodemgr', 'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [ 'web', 'job',",
"'zookeeper', 'rabbitmq', 'cassandra', ], 'webui': [ 'web', 'job', ], 'config':",
"[ 'svc-monitor', 'nodemgr', 'device-manager', 'api', 'schema', ], } WARNING =",
"WARNING = 1 CRITICAL = 2 def get_contrail_status_txt(services): try: output",
"'control', 'nodemgr', 'named', 'dns', ], 'config-database': [ 'nodemgr', 'zookeeper', 'rabbitmq',",
"== 0: group = None continue if group and len(words)",
"sudo -E contrail-status --format json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err:",
"len(words) == 0: group = None continue if group and",
"json\", shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err: message = ('CRITICAL: Could",
"= get_contrail_status_json(services) else: statuses = get_contrail_status_txt(services) for group in services:",
"in statuses: message = ('WARNING: POD {} is absent in",
"{}'. format(err.returncode, err.cmd, err.output)) print(message) sys.exit(CRITICAL) statuses = dict() group",
"shell=True).decode('UTF-8')) except subprocess.CalledProcessError as err: message = ('CRITICAL: Could not",
"print(message) sys.exit(CRITICAL) print('Contrail status OK') sys.exit() if __name__ == '__main__':",
"'api', 'schema', ], } WARNING = 1 CRITICAL = 2",
"and len(words) >= 2 and group in services: srv =",
"in the contrail-status' .format(srv)) print(message) sys.exit(WARNING) status = next(stat[srv] for",
"('CRITICAL: {} is not ready. Reason: {}' .format(srv, status)) print(message)",
"absent in the contrail-status' .format(group)) print(message) sys.exit(WARNING) for srv in",
"len(words) == 4 and words[0] == '==' and words[3] ==",
"status not in ['active', 'backup']: message = ('CRITICAL: {} is",
"'==': group = words[2] continue if len(words) == 0: group",
"list()).append( {srv: ' '.join(words[1:])}) return statuses def get_contrail_status_json(services): try: output",
"def check_contrail_status(services, version=None): if version > 1912: statuses = get_contrail_status_json(services)"
] |
[
"totalShots = 0 if \"game\" in content: if content[\"game\"]==\"starship\": if",
"import uwsgidecorators import signalfx app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type'",
"if \"shots\" in content: totalShots = content[\"shots\"] shotSubmission[\"shots\"] = totalShots",
"= request.get_json(force=True) print('Content:',content) shotSubmission = {} totalShots = 0 if",
"200 else: return jsonify({'ip':'-'}), 200 #return json.dumps({k:v for k, v",
"@app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()),",
"from flask_cors import CORS, cross_origin import simplejson as json from",
"print('Content:',content) if \"game\" in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return",
"content[\"game\"]==\"starship\": if \"shots\" in content: totalShots = content[\"shots\"] shotSubmission[\"shots\"] =",
"in content: if content[\"game\"]==\"starship\": if \"shots\" in content: totalShots =",
"app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx",
"Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 = {} counterArray",
"totalShots if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"]",
"def get_my_ip(): if 'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else:",
"= \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health')",
"\"game\" in content: if content[\"game\"]==\"starship\": if \"shots\" in content: totalShots",
"200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content = request.get_json(force=True) print('Content:',content)",
"jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}), 200 #return json.dumps({k:v for k,",
"@app.route('/health') def health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game):",
"\"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json'])",
"0 if \"game\" in content: if content[\"game\"]==\"starship\": if \"shots\" in",
"methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content = request.get_json(force=True) print('Content:',content) shotSubmission =",
"submitScores(): content = request.get_json(force=True) print('Content:',content) if \"game\" in content: if",
"dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray)",
"content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if",
"return '{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content =",
"jsonify({'ip':'-'}), 200 #return json.dumps({k:v for k, v in request.headers.items()}), 200",
"request.get_json(force=True) print('Content:',content) if \"game\" in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"])",
"#return json.dumps({k:v for k, v in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST'])",
"= row[\"ip\"] # dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"]",
"= CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row):",
"uwsgidecorators import signalfx app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors",
"\"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def",
"= content[\"shots\"] shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"]",
"return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}), 200 #return json.dumps({k:v for",
"@cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content = request.get_json(force=True) print('Content:',content) shotSubmission = {}",
"def submitScores(): content = request.get_json(force=True) print('Content:',content) if \"game\" in content:",
"@app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content = request.get_json(force=True) print('Content:',content) shotSubmission",
"return jsonify({'ip':'-'}), 200 #return json.dumps({k:v for k, v in request.headers.items()}),",
"{} counterArray = [] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"]",
"import simplejson as json from leaderboard.leaderboard import Leaderboard import uwsgidecorators",
"= {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension metricDump1[\"metric\"] = \"starship.shots\"",
"CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1",
"in content: totalShots = content[\"shots\"] shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip'",
"def health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if",
"= {} totalShots = 0 if \"game\" in content: if",
"sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 = {} counterArray =",
"returnLeaders(game): if game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}',",
"if 'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}),",
"'{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game == \"starship\":",
"if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] =",
"flask import Flask, jsonify, request from flask_cors import CORS, cross_origin",
"request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content = request.get_json(force=True)",
"@cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content = request.get_json(force=True) print('Content:',content) if \"game\" in",
"counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health(): return '{\"status\":\"OK\"}', 200",
"cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def",
"== \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200 @app.route('/submitScores', methods=['POST'])",
"if game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200",
"import signalfx app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors =",
"in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}), 200 #return",
"= 'Content-Type' cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx =",
"200 return '{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content",
"content: totalShots = content[\"shots\"] shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip' in",
"row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health(): return '{\"status\":\"OK\"}',",
"{} totalShots = 0 if \"game\" in content: if content[\"game\"]==\"starship\":",
"'Content-Type' cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector')",
"else: return jsonify({'ip':'-'}), 200 #return json.dumps({k:v for k, v in",
"@cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200",
"= signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 = {} counterArray = []",
"from flask import Flask, jsonify, request from flask_cors import CORS,",
"= [] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension",
"print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>')",
"content = request.get_json(force=True) print('Content:',content) if \"game\" in content: if content[\"game\"]==\"starship\":",
"request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return",
"signalfx app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app)",
"metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health():",
"@app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip' in request.headers: return",
"Flask, jsonify, request from flask_cors import CORS, cross_origin import simplejson",
"totalShots = content[\"shots\"] shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip' in request.headers:",
"metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension metricDump1[\"metric\"] =",
"{} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"]",
"= totalShots if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else:",
"app = Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) highscore_lb_starship",
"'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}), 200",
"shotSubmission = {} totalShots = 0 if \"game\" in content:",
"request.get_json(force=True) print('Content:',content) shotSubmission = {} totalShots = 0 if \"game\"",
"content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def",
"Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance')",
"= Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 = {}",
"import CORS, cross_origin import simplejson as json from leaderboard.leaderboard import",
"<filename>leaderboard-server/leaderboard-server.py from flask import Flask, jsonify, request from flask_cors import",
"metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] =",
"if content[\"game\"]==\"starship\": if \"shots\" in content: totalShots = content[\"shots\"] shotSubmission[\"shots\"]",
"print('Content:',content) shotSubmission = {} totalShots = 0 if \"game\" in",
"\"game\" in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200",
"content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"])",
"def returnLeaders(game): if game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return",
"k, v in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots():",
"@app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content = request.get_json(force=True) print('Content:',content) if",
"'{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content = request.get_json(force=True)",
"highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip():",
"content: if content[\"game\"]==\"starship\": if \"shots\" in content: totalShots = content[\"shots\"]",
"return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip'",
"health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game",
"cross_origin import simplejson as json from leaderboard.leaderboard import Leaderboard import",
"from leaderboard.leaderboard import Leaderboard import uwsgidecorators import signalfx app =",
"json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores():",
"= request.get_json(force=True) print('Content:',content) if \"game\" in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"],",
"[] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] # dimension metricDump1[\"metric\"]",
"import Flask, jsonify, request from flask_cors import CORS, cross_origin import",
"sfx.send(counters=counterArray) @app.route('/health') def health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def",
"game == \"starship\": return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200 @app.route('/submitScores',",
"# dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending",
"shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if __name__ ==",
"submitShots(): content = request.get_json(force=True) print('Content:',content) shotSubmission = {} totalShots =",
"= request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200",
"200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip' in request.headers:",
"shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}',",
"'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\"",
"json.dumps({k:v for k, v in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json'])",
"if \"game\" in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}',",
"signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 = {} counterArray = [] metricDump1[\"dimensions\"]",
"counterArray = [] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] = row[\"ip\"] #",
"return json.dumps(highscore_lb_starship.all_leaders()), 200 return '{}', 200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def",
"def submitShots(): content = request.get_json(force=True) print('Content:',content) shotSubmission = {} totalShots",
"= 0 if \"game\" in content: if content[\"game\"]==\"starship\": if \"shots\"",
"parseData(row): metricDump1 = {} counterArray = [] metricDump1[\"dimensions\"] = {}",
"row[\"ip\"] # dimension metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1)",
"Leaderboard import uwsgidecorators import signalfx app = Flask(__name__) app.config['CORS_HEADERS'] =",
"metricDump1[\"metric\"] = \"starship.shots\" metricDump1[\"value\"] = row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray)",
"if \"game\" in content: if content[\"game\"]==\"starship\": if \"shots\" in content:",
"as json from leaderboard.leaderboard import Leaderboard import uwsgidecorators import signalfx",
"200 #return json.dumps({k:v for k, v in request.headers.items()}), 200 @app.route('/submitShots',",
"get_my_ip(): if 'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return",
"data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health(): return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization'])",
"'{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip' in",
"CORS, cross_origin import simplejson as json from leaderboard.leaderboard import Leaderboard",
"methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}),",
"content[\"shots\"] shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] =",
"parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if __name__ == '__main__': app.run(host='0.0.0.0', port=6001)",
"methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content = request.get_json(force=True) print('Content:',content) if \"game\"",
"content = request.get_json(force=True) print('Content:',content) shotSubmission = {} totalShots = 0",
"leaderboard.leaderboard import Leaderboard import uwsgidecorators import signalfx app = Flask(__name__)",
"if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\", methods=[\"GET\"]) @cross_origin(origin='localhost',headers=['Content-Type','Authorization'])",
"in content: if content[\"game\"]==\"starship\": highscore_lb_starship.rank_member(content[\"aduser\"], content[\"score\"]) return '{\"status\":\"OK\"}', 200 @app.route(\"/get_my_ip\",",
"request from flask_cors import CORS, cross_origin import simplejson as json",
"= {} counterArray = [] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"] =",
"request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200 else: return jsonify({'ip':'-'}), 200 #return json.dumps({k:v",
"200 @app.route('/submitScores', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitScores(): content = request.get_json(force=True) print('Content:',content)",
"in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission)",
"flask_cors import CORS, cross_origin import simplejson as json from leaderboard.leaderboard",
"metricDump1 = {} counterArray = [] metricDump1[\"dimensions\"] = {} metricDump1[\"dimensions\"][\"ip\"]",
"\"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if __name__ == '__main__': app.run(host='0.0.0.0',",
"def parseData(row): metricDump1 = {} counterArray = [] metricDump1[\"dimensions\"] =",
"= row[\"shots\"] counterArray.append(metricDump1) print('Sending data:',counterArray) sfx.send(counters=counterArray) @app.route('/health') def health(): return",
"shotSubmission[\"shots\"] = totalShots if 'X-Real-Ip' in request.headers: shotSubmission[\"ip\"] = request.headers['X-Real-Ip']",
"jsonify, request from flask_cors import CORS, cross_origin import simplejson as",
"simplejson as json from leaderboard.leaderboard import Leaderboard import uwsgidecorators import",
"in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content =",
"import Leaderboard import uwsgidecorators import signalfx app = Flask(__name__) app.config['CORS_HEADERS']",
"request.headers['X-Real-Ip'] else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if",
"@cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def get_my_ip(): if 'X-Real-Ip' in request.headers: return jsonify({'ip':request.headers['X-Real-Ip']}), 200",
"json from leaderboard.leaderboard import Leaderboard import uwsgidecorators import signalfx app",
"= Flask(__name__) app.config['CORS_HEADERS'] = 'Content-Type' cors = CORS(app) highscore_lb_starship =",
"for k, v in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def",
"= \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if __name__ == '__main__':",
"else: shotSubmission[\"ip\"] = \"-\" parseData(shotSubmission) return '{\"status\":\"OK\"}', 200 if __name__",
"v in request.headers.items()}), 200 @app.route('/submitShots', methods=['POST']) @cross_origin(origin='localhost',headers=['Content-Type','application/json']) def submitShots(): content",
"\"shots\" in content: totalShots = content[\"shots\"] shotSubmission[\"shots\"] = totalShots if",
"highscore_lb_starship = Leaderboard('highscores-starship',host='redis-instance') sfx = signalfx.SignalFx(ingest_endpoint='http://otelcol:9943').ingest('token-at-collector') def parseData(row): metricDump1 =",
"200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game == \"starship\": return",
"return '{\"status\":\"OK\"}', 200 @app.route('/leaders/<game>') @cross_origin(origin='localhost',headers=['Content-Type','Authorization']) def returnLeaders(game): if game =="
] |
[
"False break # check if there are redundant points if",
"parser = _get_info_parser() args = parser.parse_args(argv) # read mesh data",
"# Parse command line arguments. parser = _get_info_parser() args =",
"mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used): print(\"ATTENTION: Some points are",
"# read mesh data mesh = read(args.infile, file_format=args.input_format) print(mesh) #",
"if there are redundant points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0],",
"be read from\") parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file",
"consistent with the points is_consistent = True for cells in",
"file format\", default=None, ) parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display",
"info(argv=None): # Parse command line arguments. parser = _get_info_parser() args",
"arrays are consistent with the points is_consistent = True for",
"is_consistent = False break # check if there are redundant",
"help=\"mesh file to be read from\") parser.add_argument( \"--input-format\", \"-i\", type=str,",
"parser = argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str,",
"help=\"input file format\", default=None, ) parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(),",
"Parse command line arguments. parser = _get_info_parser() args = parser.parse_args(argv)",
"default=None, ) parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display version information\",",
"to nonexistent points.\") is_consistent = False break # check if",
"np from .._helpers import read, reader_map from ._helpers import _get_version_text",
"point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells: point_is_used[cells.data] =",
"= _get_info_parser() args = parser.parse_args(argv) # read mesh data mesh",
"= True for cells in mesh.cells: if np.any(cells.data > mesh.points.shape[0]):",
"points is_consistent = True for cells in mesh.cells: if np.any(cells.data",
"with the points is_consistent = True for cells in mesh.cells:",
"print(\"\\nATTENTION: Inconsistent mesh. Cells refer to nonexistent points.\") is_consistent =",
"read from\") parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\",",
"command line arguments. parser = _get_info_parser() args = parser.parse_args(argv) #",
"print(\"ATTENTION: Some points are not part of any cell.\") def",
"import read, reader_map from ._helpers import _get_version_text def info(argv=None): #",
"break # check if there are redundant points if is_consistent:",
"is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells: point_is_used[cells.data]",
"\"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None, ) parser.add_argument( \"--version\",",
"are redundant points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for",
"in mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells",
"cells in mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh.",
"mesh. Cells refer to nonexistent points.\") is_consistent = False break",
"def info(argv=None): # Parse command line arguments. parser = _get_info_parser()",
"for cells in mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent",
"True if np.any(~point_is_used): print(\"ATTENTION: Some points are not part of",
"._helpers import _get_version_text def info(argv=None): # Parse command line arguments.",
"description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh file to",
"\"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display version information\", ) return parser",
"= parser.parse_args(argv) # read mesh data mesh = read(args.infile, file_format=args.input_format)",
"for cells in mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used): print(\"ATTENTION:",
"= argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh",
"print(mesh) # check if the cell arrays are consistent with",
"read, reader_map from ._helpers import _get_version_text def info(argv=None): # Parse",
"part of any cell.\") def _get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print",
"format\", default=None, ) parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display version",
"Cells refer to nonexistent points.\") is_consistent = False break #",
"are consistent with the points is_consistent = True for cells",
"there are redundant points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool)",
"np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells refer to nonexistent",
"to be read from\") parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input",
"points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells in",
".._helpers import read, reader_map from ._helpers import _get_version_text def info(argv=None):",
"the cell arrays are consistent with the points is_consistent =",
"= True if np.any(~point_is_used): print(\"ATTENTION: Some points are not part",
"np.any(~point_is_used): print(\"ATTENTION: Some points are not part of any cell.\")",
"# check if the cell arrays are consistent with the",
"mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh file to be",
"not part of any cell.\") def _get_info_parser(): parser = argparse.ArgumentParser(",
"reader_map from ._helpers import _get_version_text def info(argv=None): # Parse command",
"mesh = read(args.infile, file_format=args.input_format) print(mesh) # check if the cell",
"Inconsistent mesh. Cells refer to nonexistent points.\") is_consistent = False",
"\"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None, ) parser.add_argument(",
"args = parser.parse_args(argv) # read mesh data mesh = read(args.infile,",
"line arguments. parser = _get_info_parser() args = parser.parse_args(argv) # read",
"parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display version information\", ) return",
"import argparse import numpy as np from .._helpers import read,",
"parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None, )",
"as np from .._helpers import read, reader_map from ._helpers import",
"points.\") is_consistent = False break # check if there are",
"argparse import numpy as np from .._helpers import read, reader_map",
"formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh file to be read from\")",
"mesh data mesh = read(args.infile, file_format=args.input_format) print(mesh) # check if",
"Some points are not part of any cell.\") def _get_info_parser():",
"cells in mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used): print(\"ATTENTION: Some",
"read(args.infile, file_format=args.input_format) print(mesh) # check if the cell arrays are",
") parser.add_argument( \"--version\", \"-v\", action=\"version\", version=_get_version_text(), help=\"display version information\", )",
"info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh file to be read",
"of any cell.\") def _get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print mesh",
"cell.\") def _get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter",
"data mesh = read(args.infile, file_format=args.input_format) print(mesh) # check if the",
"check if the cell arrays are consistent with the points",
"import numpy as np from .._helpers import read, reader_map from",
"# check if there are redundant points if is_consistent: point_is_used",
"type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None, ) parser.add_argument( \"--version\", \"-v\",",
"arguments. parser = _get_info_parser() args = parser.parse_args(argv) # read mesh",
"_get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\",",
"in mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used): print(\"ATTENTION: Some points",
"parser.add_argument(\"infile\", type=str, help=\"mesh file to be read from\") parser.add_argument( \"--input-format\",",
"True for cells in mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION:",
"check if there are redundant points if is_consistent: point_is_used =",
"choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None, ) parser.add_argument( \"--version\", \"-v\", action=\"version\",",
"from ._helpers import _get_version_text def info(argv=None): # Parse command line",
"file_format=args.input_format) print(mesh) # check if the cell arrays are consistent",
"import _get_version_text def info(argv=None): # Parse command line arguments. parser",
"redundant points if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells",
"def _get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter )",
"parser.parse_args(argv) # read mesh data mesh = read(args.infile, file_format=args.input_format) print(mesh)",
"cell arrays are consistent with the points is_consistent = True",
"is_consistent = True for cells in mesh.cells: if np.any(cells.data >",
"nonexistent points.\") is_consistent = False break # check if there",
"from\") parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())), help=\"input file format\", default=None,",
"> mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells refer to nonexistent points.\")",
"are not part of any cell.\") def _get_info_parser(): parser =",
"= np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells: point_is_used[cells.data] = True",
"argparse.ArgumentParser( description=(\"Print mesh info.\"), formatter_class=argparse.RawTextHelpFormatter ) parser.add_argument(\"infile\", type=str, help=\"mesh file",
"_get_version_text def info(argv=None): # Parse command line arguments. parser =",
"_get_info_parser() args = parser.parse_args(argv) # read mesh data mesh =",
"read mesh data mesh = read(args.infile, file_format=args.input_format) print(mesh) # check",
"file to be read from\") parser.add_argument( \"--input-format\", \"-i\", type=str, choices=sorted(list(reader_map.keys())),",
"if np.any(~point_is_used): print(\"ATTENTION: Some points are not part of any",
") parser.add_argument(\"infile\", type=str, help=\"mesh file to be read from\") parser.add_argument(",
"the points is_consistent = True for cells in mesh.cells: if",
"= read(args.infile, file_format=args.input_format) print(mesh) # check if the cell arrays",
"dtype=bool) for cells in mesh.cells: point_is_used[cells.data] = True if np.any(~point_is_used):",
"mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells refer to nonexistent points.\") is_consistent",
"= False break # check if there are redundant points",
"from .._helpers import read, reader_map from ._helpers import _get_version_text def",
"if the cell arrays are consistent with the points is_consistent",
"mesh.cells: if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells refer",
"if is_consistent: point_is_used = np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells:",
"numpy as np from .._helpers import read, reader_map from ._helpers",
"points are not part of any cell.\") def _get_info_parser(): parser",
"if np.any(cells.data > mesh.points.shape[0]): print(\"\\nATTENTION: Inconsistent mesh. Cells refer to",
"type=str, help=\"mesh file to be read from\") parser.add_argument( \"--input-format\", \"-i\",",
"np.zeros(mesh.points.shape[0], dtype=bool) for cells in mesh.cells: point_is_used[cells.data] = True if",
"point_is_used[cells.data] = True if np.any(~point_is_used): print(\"ATTENTION: Some points are not",
"any cell.\") def _get_info_parser(): parser = argparse.ArgumentParser( description=(\"Print mesh info.\"),",
"refer to nonexistent points.\") is_consistent = False break # check"
] |
[
"- zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone \"\"\" #",
"the executors. It essentially zips the Python packages installed by",
"root_dir=zip_from, # the dir (relative to root dir) which we",
"path to the resulting zipped file (without the suffix) base_name=zipped_fpath,",
"= /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone \"\"\" # change this",
"dir (relative to root dir) which we want to zip",
"base_dir=zip_target, ) # add the files to the executors SS.SPARK().sparkContext.addPyFile(f'{zipped_fpath}.zip')",
"the current PySpark context E.g. if we want to submit",
"implies .zip suffix format='zip', # the root dir from where",
"This method creates a zip of the code to be",
"the code to be sent to the executors. It essentially",
"resulting filename # specifies the format --> implies .zip suffix",
"the Python packages installed by PIP and submits them via",
"f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( #",
"in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'):",
"can do use `import metaphone` and use its methods inside",
"as SS def add_zipped_dependency(zip_from, zip_target): \"\"\" This method creates a",
"E.g. if we want to submit \"metaphone\" package so that",
"essentially zips the Python packages installed by PIP and submits",
"zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip')",
"from CCSLink import Spark_Session as SS def add_zipped_dependency(zip_from, zip_target): \"\"\"",
"Spark_Session as SS def add_zipped_dependency(zip_from, zip_target): \"\"\" This method creates",
"CCSLink import Spark_Session as SS def add_zipped_dependency(zip_from, zip_target): \"\"\" This",
"os, shutil from CCSLink import Spark_Session as SS def add_zipped_dependency(zip_from,",
"be sent to the executors. It essentially zips the Python",
"methods inside UDF, we run this method with: - zip_from",
"/home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone \"\"\" # change this to",
"'.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( # path to the resulting",
"(all files in the final zip will have this prefix)",
"we can do use `import metaphone` and use its methods",
".zip suffix format='zip', # the root dir from where we",
"suffix) base_name=zipped_fpath, # resulting filename # specifies the format -->",
"in the current PySpark context E.g. if we want to",
"PIP and submits them via addPyFile in the current PySpark",
"want to zip # (all files in the final zip",
"# path to the resulting zipped file (without the suffix)",
"<reponame>Data-Linkage/ccslink<gh_stars>0 import os, shutil from CCSLink import Spark_Session as SS",
"file (without the suffix) base_name=zipped_fpath, # resulting filename # specifies",
"- zip_target = metaphone \"\"\" # change this to a",
"suffix format='zip', # the root dir from where we want",
"change this to a path in your project zipped_fpath =",
"# (all files in the final zip will have this",
"shutil from CCSLink import Spark_Session as SS def add_zipped_dependency(zip_from, zip_target):",
"of the code to be sent to the executors. It",
"sent to the executors. It essentially zips the Python packages",
"submit \"metaphone\" package so that we can do use `import",
"its methods inside UDF, we run this method with: -",
"SS def add_zipped_dependency(zip_from, zip_target): \"\"\" This method creates a zip",
"will have this prefix) base_dir=zip_target, ) # add the files",
"zip_target = metaphone \"\"\" # change this to a path",
"# specifies the format --> implies .zip suffix format='zip', #",
"metaphone \"\"\" # change this to a path in your",
"method creates a zip of the code to be sent",
"zips the Python packages installed by PIP and submits them",
"so that we can do use `import metaphone` and use",
"addPyFile in the current PySpark context E.g. if we want",
"package so that we can do use `import metaphone` and",
"in the final zip will have this prefix) base_dir=zip_target, )",
"the final zip will have this prefix) base_dir=zip_target, ) #",
"import Spark_Session as SS def add_zipped_dependency(zip_from, zip_target): \"\"\" This method",
"via addPyFile in the current PySpark context E.g. if we",
"PySpark context E.g. if we want to submit \"metaphone\" package",
"this method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target =",
"submits them via addPyFile in the current PySpark context E.g.",
"to a path in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if",
"we run this method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ -",
"`import metaphone` and use its methods inside UDF, we run",
"context E.g. if we want to submit \"metaphone\" package so",
"we want to zip root_dir=zip_from, # the dir (relative to",
"# change this to a path in your project zipped_fpath",
"= metaphone \"\"\" # change this to a path in",
"# resulting filename # specifies the format --> implies .zip",
"zip root_dir=zip_from, # the dir (relative to root dir) which",
"to root dir) which we want to zip # (all",
"def add_zipped_dependency(zip_from, zip_target): \"\"\" This method creates a zip of",
"format='zip', # the root dir from where we want to",
"# the root dir from where we want to zip",
"to the executors. It essentially zips the Python packages installed",
"to the resulting zipped file (without the suffix) base_name=zipped_fpath, #",
"shutil.make_archive( # path to the resulting zipped file (without the",
"specifies the format --> implies .zip suffix format='zip', # the",
"--> implies .zip suffix format='zip', # the root dir from",
"your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath",
"where we want to zip root_dir=zip_from, # the dir (relative",
"use `import metaphone` and use its methods inside UDF, we",
"project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath +",
"to be sent to the executors. It essentially zips the",
"the dir (relative to root dir) which we want to",
"add_zipped_dependency(zip_from, zip_target): \"\"\" This method creates a zip of the",
"dir) which we want to zip # (all files in",
"want to zip root_dir=zip_from, # the dir (relative to root",
"want to submit \"metaphone\" package so that we can do",
"= f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive(",
"code to be sent to the executors. It essentially zips",
"and use its methods inside UDF, we run this method",
"+ '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( # path to the",
"have this prefix) base_dir=zip_target, ) # add the files to",
"+ '.zip') shutil.make_archive( # path to the resulting zipped file",
"inside UDF, we run this method with: - zip_from =",
"a path in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath",
"import os, shutil from CCSLink import Spark_Session as SS def",
"by PIP and submits them via addPyFile in the current",
"to zip # (all files in the final zip will",
"format --> implies .zip suffix format='zip', # the root dir",
"method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone",
"base_name=zipped_fpath, # resulting filename # specifies the format --> implies",
"which we want to zip # (all files in the",
"\"metaphone\" package so that we can do use `import metaphone`",
"a zip of the code to be sent to the",
"(without the suffix) base_name=zipped_fpath, # resulting filename # specifies the",
"and submits them via addPyFile in the current PySpark context",
"'.zip') shutil.make_archive( # path to the resulting zipped file (without",
"executors. It essentially zips the Python packages installed by PIP",
"this prefix) base_dir=zip_target, ) # add the files to the",
"UDF, we run this method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/",
"root dir) which we want to zip # (all files",
"creates a zip of the code to be sent to",
"this to a path in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}'",
"to submit \"metaphone\" package so that we can do use",
"the root dir from where we want to zip root_dir=zip_from,",
"we want to zip # (all files in the final",
"(relative to root dir) which we want to zip #",
"run this method with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target",
"packages installed by PIP and submits them via addPyFile in",
"the suffix) base_name=zipped_fpath, # resulting filename # specifies the format",
"zipped file (without the suffix) base_name=zipped_fpath, # resulting filename #",
"zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone \"\"\" # change",
"that we can do use `import metaphone` and use its",
"zip_target): \"\"\" This method creates a zip of the code",
"current PySpark context E.g. if we want to submit \"metaphone\"",
"if we want to submit \"metaphone\" package so that we",
"\"\"\" # change this to a path in your project",
"resulting zipped file (without the suffix) base_name=zipped_fpath, # resulting filename",
"os.remove(zipped_fpath + '.zip') shutil.make_archive( # path to the resulting zipped",
"filename # specifies the format --> implies .zip suffix format='zip',",
"from where we want to zip root_dir=zip_from, # the dir",
"prefix) base_dir=zip_target, ) # add the files to the executors",
"the resulting zipped file (without the suffix) base_name=zipped_fpath, # resulting",
"zip of the code to be sent to the executors.",
"os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( # path to",
"them via addPyFile in the current PySpark context E.g. if",
"final zip will have this prefix) base_dir=zip_target, ) # add",
"metaphone` and use its methods inside UDF, we run this",
"zip will have this prefix) base_dir=zip_target, ) # add the",
"It essentially zips the Python packages installed by PIP and",
"files in the final zip will have this prefix) base_dir=zip_target,",
"use its methods inside UDF, we run this method with:",
"Python packages installed by PIP and submits them via addPyFile",
"path in your project zipped_fpath = f'/home/cdsw/zipped_packages/{zip_target}' if os.path.exists(zipped_fpath +",
"\"\"\" This method creates a zip of the code to",
"with: - zip_from = /home/cdsw/.local/lib/python3.6/site-packages/ - zip_target = metaphone \"\"\"",
"to zip root_dir=zip_from, # the dir (relative to root dir)",
"root dir from where we want to zip root_dir=zip_from, #",
"we want to submit \"metaphone\" package so that we can",
"dir from where we want to zip root_dir=zip_from, # the",
"do use `import metaphone` and use its methods inside UDF,",
"the format --> implies .zip suffix format='zip', # the root",
"# the dir (relative to root dir) which we want",
"zip # (all files in the final zip will have",
"if os.path.exists(zipped_fpath + '.zip'): os.remove(zipped_fpath + '.zip') shutil.make_archive( # path",
"installed by PIP and submits them via addPyFile in the"
] |
[
"function of the angle between. three consecutively bonded atoms (referred",
"which sorts the atoms and bonds in a way which",
"down he simulation). To avoid this, I define a \"canonical_order\"",
"# # *---*---* => 1st bond connects atoms 0 and",
"= match[0][2] # match[1][0:1] contains the ID numbers for the",
"< atom2: # return ((atom0, atom1, atom2), (bond0, bond1)) same",
"list of atom/bond ids in the matches-found-so-far, before it is",
"atom2 = match[0][2] # match[1][0:1] contains the ID numbers for",
"0,1,2 AS WELL AS an interaction between 2,1,0. So we",
"will be tested against the list of atom/bond ids in",
"atoms. If not then we create a new one.) \"\"\"",
"a function of the angle between. three consecutively bonded atoms",
"between 0-1-2 and 2-1-0: def canonical_order(match): \"\"\" Before defining a",
"between atoms 0,1,2 AS WELL AS an interaction between 2,1,0.",
"that the first atom has a always has a lower",
"contains the ID numbers for the 3 atoms in the",
"Ugraph except (SystemError, ValueError): # not installed as a package",
"1 # 0 1 2 2nd bond connects atoms 1",
"0,1,2). This angle does not change when swapping the atoms",
"custom file. # To find 3-body \"angle\" interactions, we would",
"to see if an interaction between these same 3 atoms",
"which is consistent with the symmetry of the interaction being",
"this this, we will create many unnecessary redundant interactions (which",
"The next function eliminates the redundancy between 0-1-2 and 2-1-0:",
"match[1][1] if atom0 < atom2: # return ((atom0, atom1, atom2),",
"To find 3-body \"angle\" interactions, we would use this subgraph:",
"we sort the atoms and bonds so that the first",
"interaction is a function of the angle between. three consecutively",
"a different, but equivalent order). If we don't check for",
"generated... Later the re-ordered list of atom and bond ids",
"not installed as a package from nbody_graph_search import Ugraph #",
"new interaction, we must check to see if an interaction",
"of interactions found so far. Note that the energy of",
"the redundancy between 0-1-2 and 2-1-0: def canonical_order(match): \"\"\" Before",
"interaction between atoms 0,1,2 AS WELL AS an interaction between",
"= match[1][1] if atom0 < atom2: # return ((atom0, atom1,",
"slow down he simulation). To avoid this, I define a",
"see if we have already defined an interaction between these",
"the energy of an angle interaction is a function of",
"the atoms at either end (0 and 2). So it",
"a \"canonical_order\" function which sorts the atoms and bonds in",
"bond1)) same thing as: return match else: return ((atom2, atom1,",
"before it is added to the list of interactions found",
"if we have already defined an interaction between these 3",
"for the 2 bonds bond0 = match[1][0] bond1 = match[1][1]",
"# not installed as a package from nbody_graph_search import Ugraph",
"we will check to see if we have already defined",
"0 and 1 # 0 1 2 2nd bond connects",
"atoms 0 and 1 # 0 1 2 2nd bond",
"bond1 = match[1][1] if atom0 < atom2: # return ((atom0,",
"at 0, not 1) # The next function eliminates the",
"ID numbers for the 2 bonds bond0 = match[1][0] bond1",
"generated by moltemplate # by default. It can be overridden",
"the third atom. (Later we will check to see if",
"check to see if we have already defined an interaction",
"2 # bond_pattern = Ugraph([(0, 1), (1, 2)]) # (Ugraph",
"1 and 2 # bond_pattern = Ugraph([(0, 1), (1, 2)])",
"this, I define a \"canonical_order\" function which sorts the atoms",
"interactions found so far. Note that the energy of an",
"define a separate 3-body angle interaction between atoms 0,1,2 AS",
"This angle does not change when swapping the atoms at",
"we would use this subgraph: # # # *---*---* =>",
"not make sense to define a separate 3-body angle interaction",
"\"angle\" interactions, we would use this subgraph: # # #",
"atom2: # return ((atom0, atom1, atom2), (bond0, bond1)) same thing",
"# This file defines how 3-body angle interactions are generated",
"three consecutively bonded atoms (referred to here as: 0,1,2). This",
"added to the list of interactions found so far. Note",
"the angle between. three consecutively bonded atoms (referred to here",
"next function eliminates the redundancy between 0-1-2 and 2-1-0: def",
"atom0 < atom2: # return ((atom0, atom1, atom2), (bond0, bond1))",
"redundancy between 0-1-2 and 2-1-0: def canonical_order(match): \"\"\" Before defining",
"will create many unnecessary redundant interactions (which can slow down",
"but equivalent order). If we don't check for this this,",
"create many unnecessary redundant interactions (which can slow down he",
"AS an interaction between 2,1,0. So we sort the atoms",
"be overridden by supplying your own custom file. # To",
"far. Note that the energy of an angle interaction is",
"1), (1, 2)]) # (Ugraph atom indices begin at 0,",
"we will create many unnecessary redundant interactions (which can slow",
"check to see if an interaction between these same 3",
".nbody_graph_search import Ugraph except (SystemError, ValueError): # not installed as",
"of atom/bond ids in the matches-found-so-far, before it is added",
"3 atoms in the match atom0 = match[0][0] atom1 =",
"Before defining a new interaction, we must check to see",
"and 2). So it does not make sense to define",
"already been created (perhaps listed in a different, but equivalent",
"with the symmetry of the interaction being generated... Later the",
"angle interaction is a function of the angle between. three",
"canonical_order(match): \"\"\" Before defining a new interaction, we must check",
"and bond ids will be tested against the list of",
"angle interaction between atoms 0,1,2 AS WELL AS an interaction",
"subgraph: # # # *---*---* => 1st bond connects atoms",
"lower atomID than the third atom. (Later we will check",
"use this subgraph: # # # *---*---* => 1st bond",
"many unnecessary redundant interactions (which can slow down he simulation).",
"has a lower atomID than the third atom. (Later we",
"ValueError): # not installed as a package from nbody_graph_search import",
"(0 and 2). So it does not make sense to",
"So we sort the atoms and bonds so that the",
"atoms and bonds in a way which is consistent with",
"2)]) # (Ugraph atom indices begin at 0, not 1)",
"the list of interactions found so far. Note that the",
"here as: 0,1,2). This angle does not change when swapping",
"(perhaps listed in a different, but equivalent order). If we",
"of the angle between. three consecutively bonded atoms (referred to",
"atoms and bonds so that the first atom has a",
"a always has a lower atomID than the third atom.",
"It can be overridden by supplying your own custom file.",
"as a package from nbody_graph_search import Ugraph # This file",
"has a always has a lower atomID than the third",
"return ((atom0, atom1, atom2), (bond0, bond1)) same thing as: return",
"between. three consecutively bonded atoms (referred to here as: 0,1,2).",
"overridden by supplying your own custom file. # To find",
"the match atom0 = match[0][0] atom1 = match[0][1] atom2 =",
"atoms 1 and 2 # bond_pattern = Ugraph([(0, 1), (1,",
"sorts the atoms and bonds in a way which is",
"bond ids will be tested against the list of atom/bond",
"the ID numbers for the 3 atoms in the match",
"installed as a package from nbody_graph_search import Ugraph # This",
"3-body \"angle\" interactions, we would use this subgraph: # #",
"2-1-0: def canonical_order(match): \"\"\" Before defining a new interaction, we",
"in a way which is consistent with the symmetry of",
"then we create a new one.) \"\"\" # match[0][0:2] contains",
"equivalent order). If we don't check for this this, we",
"= match[0][1] atom2 = match[0][2] # match[1][0:1] contains the ID",
"than the third atom. (Later we will check to see",
"find 3-body \"angle\" interactions, we would use this subgraph: #",
"2 2nd bond connects atoms 1 and 2 # bond_pattern",
"to here as: 0,1,2). This angle does not change when",
"see if an interaction between these same 3 atoms has",
"of atom and bond ids will be tested against the",
"atoms (referred to here as: 0,1,2). This angle does not",
"of an angle interaction is a function of the angle",
"the atoms and bonds in a way which is consistent",
"list of atom and bond ids will be tested against",
"0 1 2 2nd bond connects atoms 1 and 2",
"def canonical_order(match): \"\"\" Before defining a new interaction, we must",
"a separate 3-body angle interaction between atoms 0,1,2 AS WELL",
"Note that the energy of an angle interaction is a",
"and bonds so that the first atom has a always",
"new one.) \"\"\" # match[0][0:2] contains the ID numbers for",
"connects atoms 0 and 1 # 0 1 2 2nd",
"import Ugraph except (SystemError, ValueError): # not installed as a",
"indices begin at 0, not 1) # The next function",
"found so far. Note that the energy of an angle",
"ids in the matches-found-so-far, before it is added to the",
"atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2] #",
"an interaction between 2,1,0. So we sort the atoms and",
"bond connects atoms 1 and 2 # bond_pattern = Ugraph([(0,",
"defines how 3-body angle interactions are generated by moltemplate #",
"bonds in a way which is consistent with the symmetry",
"ID numbers for the 3 atoms in the match atom0",
"have already defined an interaction between these 3 atoms. If",
"(SystemError, ValueError): # not installed as a package from nbody_graph_search",
"list of interactions found so far. Note that the energy",
"default. It can be overridden by supplying your own custom",
"# bond_pattern = Ugraph([(0, 1), (1, 2)]) # (Ugraph atom",
"the 3 atoms in the match atom0 = match[0][0] atom1",
"make sense to define a separate 3-body angle interaction between",
"between these 3 atoms. If not then we create a",
"and bonds in a way which is consistent with the",
"= match[1][0] bond1 = match[1][1] if atom0 < atom2: #",
"# by default. It can be overridden by supplying your",
"check for this this, we will create many unnecessary redundant",
"own custom file. # To find 3-body \"angle\" interactions, we",
"swapping the atoms at either end (0 and 2). So",
"Later the re-ordered list of atom and bond ids will",
"the first atom has a always has a lower atomID",
"# The next function eliminates the redundancy between 0-1-2 and",
"# # # *---*---* => 1st bond connects atoms 0",
"I define a \"canonical_order\" function which sorts the atoms and",
"a package from nbody_graph_search import Ugraph # This file defines",
"bonds bond0 = match[1][0] bond1 = match[1][1] if atom0 <",
"2,1,0. So we sort the atoms and bonds so that",
"by moltemplate # by default. It can be overridden by",
"so far. Note that the energy of an angle interaction",
"(Ugraph atom indices begin at 0, not 1) # The",
"match[0][2] # match[1][0:1] contains the ID numbers for the 2",
"the interaction being generated... Later the re-ordered list of atom",
"begin at 0, not 1) # The next function eliminates",
"does not change when swapping the atoms at either end",
"to the list of interactions found so far. Note that",
"in the matches-found-so-far, before it is added to the list",
"don't check for this this, we will create many unnecessary",
"# To find 3-body \"angle\" interactions, we would use this",
"atom/bond ids in the matches-found-so-far, before it is added to",
"atom1, atom2), (bond0, bond1)) same thing as: return match else:",
"atom indices begin at 0, not 1) # The next",
"defining a new interaction, we must check to see if",
"except (SystemError, ValueError): # not installed as a package from",
"\"canonical_order\" function which sorts the atoms and bonds in a",
"as: 0,1,2). This angle does not change when swapping the",
"match atom0 = match[0][0] atom1 = match[0][1] atom2 = match[0][2]",
"simulation). To avoid this, I define a \"canonical_order\" function which",
"it does not make sense to define a separate 3-body",
"match[1][0:1] contains the ID numbers for the 2 bonds bond0",
"interaction between these same 3 atoms has already been created",
"atom has a always has a lower atomID than the",
"atom and bond ids will be tested against the list",
"connects atoms 1 and 2 # bond_pattern = Ugraph([(0, 1),",
"order). If we don't check for this this, we will",
"at either end (0 and 2). So it does not",
"ids will be tested against the list of atom/bond ids",
"between 2,1,0. So we sort the atoms and bonds so",
"bonded atoms (referred to here as: 0,1,2). This angle does",
"can be overridden by supplying your own custom file. #",
"thing as: return match else: return ((atom2, atom1, atom0), (bond1,",
"does not make sense to define a separate 3-body angle",
"so that the first atom has a always has a",
"if atom0 < atom2: # return ((atom0, atom1, atom2), (bond0,",
"<reponame>Mopolino8/moltemplate<filename>moltemplate/nbody_Angles.py try: from .nbody_graph_search import Ugraph except (SystemError, ValueError): #",
"atoms 0,1,2 AS WELL AS an interaction between 2,1,0. So",
"must check to see if an interaction between these same",
"AS WELL AS an interaction between 2,1,0. So we sort",
"not 1) # The next function eliminates the redundancy between",
"this subgraph: # # # *---*---* => 1st bond connects",
"sense to define a separate 3-body angle interaction between atoms",
"the symmetry of the interaction being generated... Later the re-ordered",
"a new one.) \"\"\" # match[0][0:2] contains the ID numbers",
"((atom0, atom1, atom2), (bond0, bond1)) same thing as: return match",
"redundant interactions (which can slow down he simulation). To avoid",
"(1, 2)]) # (Ugraph atom indices begin at 0, not",
"always has a lower atomID than the third atom. (Later",
"3 atoms. If not then we create a new one.)",
"If we don't check for this this, we will create",
"for this this, we will create many unnecessary redundant interactions",
"match[0][0:2] contains the ID numbers for the 3 atoms in",
"we don't check for this this, we will create many",
"of the interaction being generated... Later the re-ordered list of",
"if an interaction between these same 3 atoms has already",
"If not then we create a new one.) \"\"\" #",
"tested against the list of atom/bond ids in the matches-found-so-far,",
"*---*---* => 1st bond connects atoms 0 and 1 #",
"not change when swapping the atoms at either end (0",
"atoms in the match atom0 = match[0][0] atom1 = match[0][1]",
"a way which is consistent with the symmetry of the",
"1 2 2nd bond connects atoms 1 and 2 #",
"So it does not make sense to define a separate",
"by default. It can be overridden by supplying your own",
"2). So it does not make sense to define a",
"we create a new one.) \"\"\" # match[0][0:2] contains the",
"interaction, we must check to see if an interaction between",
"and 1 # 0 1 2 2nd bond connects atoms",
"# (Ugraph atom indices begin at 0, not 1) #",
"are generated by moltemplate # by default. It can be",
"create a new one.) \"\"\" # match[0][0:2] contains the ID",
"# 0 1 2 2nd bond connects atoms 1 and",
"match[0][1] atom2 = match[0][2] # match[1][0:1] contains the ID numbers",
"import Ugraph # This file defines how 3-body angle interactions",
"this, we will create many unnecessary redundant interactions (which can",
"a lower atomID than the third atom. (Later we will",
"being generated... Later the re-ordered list of atom and bond",
"change when swapping the atoms at either end (0 and",
"(bond0, bond1)) same thing as: return match else: return ((atom2,",
"is consistent with the symmetry of the interaction being generated...",
"0-1-2 and 2-1-0: def canonical_order(match): \"\"\" Before defining a new",
"he simulation). To avoid this, I define a \"canonical_order\" function",
"same thing as: return match else: return ((atom2, atom1, atom0),",
"an interaction between these same 3 atoms has already been",
"function eliminates the redundancy between 0-1-2 and 2-1-0: def canonical_order(match):",
"1st bond connects atoms 0 and 1 # 0 1",
"to see if we have already defined an interaction between",
"match[0][0] atom1 = match[0][1] atom2 = match[0][2] # match[1][0:1] contains",
"defined an interaction between these 3 atoms. If not then",
"atomID than the third atom. (Later we will check to",
"3-body angle interaction between atoms 0,1,2 AS WELL AS an",
"1) # The next function eliminates the redundancy between 0-1-2",
"consistent with the symmetry of the interaction being generated... Later",
"numbers for the 2 bonds bond0 = match[1][0] bond1 =",
"consecutively bonded atoms (referred to here as: 0,1,2). This angle",
"from nbody_graph_search import Ugraph # This file defines how 3-body",
"# *---*---* => 1st bond connects atoms 0 and 1",
"WELL AS an interaction between 2,1,0. So we sort the",
"# match[1][0:1] contains the ID numbers for the 2 bonds",
"(which can slow down he simulation). To avoid this, I",
"third atom. (Later we will check to see if we",
"# match[0][0:2] contains the ID numbers for the 3 atoms",
"been created (perhaps listed in a different, but equivalent order).",
"angle between. three consecutively bonded atoms (referred to here as:",
"different, but equivalent order). If we don't check for this",
"can slow down he simulation). To avoid this, I define",
"a new interaction, we must check to see if an",
"re-ordered list of atom and bond ids will be tested",
"bond connects atoms 0 and 1 # 0 1 2",
"and 2 # bond_pattern = Ugraph([(0, 1), (1, 2)]) #",
"= match[0][0] atom1 = match[0][1] atom2 = match[0][2] # match[1][0:1]",
"# return ((atom0, atom1, atom2), (bond0, bond1)) same thing as:",
"created (perhaps listed in a different, but equivalent order). If",
"interactions (which can slow down he simulation). To avoid this,",
"angle interactions are generated by moltemplate # by default. It",
"will check to see if we have already defined an",
"avoid this, I define a \"canonical_order\" function which sorts the",
"the re-ordered list of atom and bond ids will be",
"from .nbody_graph_search import Ugraph except (SystemError, ValueError): # not installed",
"2nd bond connects atoms 1 and 2 # bond_pattern =",
"we must check to see if an interaction between these",
"to define a separate 3-body angle interaction between atoms 0,1,2",
"the atoms and bonds so that the first atom has",
"atom. (Later we will check to see if we have",
"is added to the list of interactions found so far.",
"be tested against the list of atom/bond ids in the",
"3 atoms has already been created (perhaps listed in a",
"package from nbody_graph_search import Ugraph # This file defines how",
"either end (0 and 2). So it does not make",
"=> 1st bond connects atoms 0 and 1 # 0",
"is a function of the angle between. three consecutively bonded",
"your own custom file. # To find 3-body \"angle\" interactions,",
"these same 3 atoms has already been created (perhaps listed",
"the 2 bonds bond0 = match[1][0] bond1 = match[1][1] if",
"interactions are generated by moltemplate # by default. It can",
"numbers for the 3 atoms in the match atom0 =",
"same 3 atoms has already been created (perhaps listed in",
"0, not 1) # The next function eliminates the redundancy",
"already defined an interaction between these 3 atoms. If not",
"match[1][0] bond1 = match[1][1] if atom0 < atom2: # return",
"Ugraph # This file defines how 3-body angle interactions are",
"atoms at either end (0 and 2). So it does",
"as: return match else: return ((atom2, atom1, atom0), (bond1, bond0))",
"the list of atom/bond ids in the matches-found-so-far, before it",
"atoms has already been created (perhaps listed in a different,",
"the ID numbers for the 2 bonds bond0 = match[1][0]",
"these 3 atoms. If not then we create a new",
"bonds so that the first atom has a always has",
"has already been created (perhaps listed in a different, but",
"in the match atom0 = match[0][0] atom1 = match[0][1] atom2",
"bond0 = match[1][0] bond1 = match[1][1] if atom0 < atom2:",
"define a \"canonical_order\" function which sorts the atoms and bonds",
"matches-found-so-far, before it is added to the list of interactions",
"atom2), (bond0, bond1)) same thing as: return match else: return",
"for the 3 atoms in the match atom0 = match[0][0]",
"file. # To find 3-body \"angle\" interactions, we would use",
"end (0 and 2). So it does not make sense",
"contains the ID numbers for the 2 bonds bond0 =",
"\"\"\" # match[0][0:2] contains the ID numbers for the 3",
"To avoid this, I define a \"canonical_order\" function which sorts",
"interaction between 2,1,0. So we sort the atoms and bonds",
"2 bonds bond0 = match[1][0] bond1 = match[1][1] if atom0",
"an angle interaction is a function of the angle between.",
"3-body angle interactions are generated by moltemplate # by default.",
"interactions, we would use this subgraph: # # # *---*---*",
"(Later we will check to see if we have already",
"we have already defined an interaction between these 3 atoms.",
"when swapping the atoms at either end (0 and 2).",
"symmetry of the interaction being generated... Later the re-ordered list",
"supplying your own custom file. # To find 3-body \"angle\"",
"and 2-1-0: def canonical_order(match): \"\"\" Before defining a new interaction,",
"against the list of atom/bond ids in the matches-found-so-far, before",
"interaction between these 3 atoms. If not then we create",
"This file defines how 3-body angle interactions are generated by",
"it is added to the list of interactions found so",
"an interaction between these 3 atoms. If not then we",
"= Ugraph([(0, 1), (1, 2)]) # (Ugraph atom indices begin",
"unnecessary redundant interactions (which can slow down he simulation). To",
"between these same 3 atoms has already been created (perhaps",
"function which sorts the atoms and bonds in a way",
"by supplying your own custom file. # To find 3-body",
"eliminates the redundancy between 0-1-2 and 2-1-0: def canonical_order(match): \"\"\"",
"not then we create a new one.) \"\"\" # match[0][0:2]",
"nbody_graph_search import Ugraph # This file defines how 3-body angle",
"atom1 = match[0][1] atom2 = match[0][2] # match[1][0:1] contains the",
"in a different, but equivalent order). If we don't check",
"that the energy of an angle interaction is a function",
"how 3-body angle interactions are generated by moltemplate # by",
"(referred to here as: 0,1,2). This angle does not change",
"first atom has a always has a lower atomID than",
"would use this subgraph: # # # *---*---* => 1st",
"one.) \"\"\" # match[0][0:2] contains the ID numbers for the",
"separate 3-body angle interaction between atoms 0,1,2 AS WELL AS",
"moltemplate # by default. It can be overridden by supplying",
"listed in a different, but equivalent order). If we don't",
"way which is consistent with the symmetry of the interaction",
"file defines how 3-body angle interactions are generated by moltemplate",
"energy of an angle interaction is a function of the",
"angle does not change when swapping the atoms at either",
"the matches-found-so-far, before it is added to the list of",
"sort the atoms and bonds so that the first atom",
"Ugraph([(0, 1), (1, 2)]) # (Ugraph atom indices begin at",
"bond_pattern = Ugraph([(0, 1), (1, 2)]) # (Ugraph atom indices",
"\"\"\" Before defining a new interaction, we must check to",
"interaction being generated... Later the re-ordered list of atom and",
"try: from .nbody_graph_search import Ugraph except (SystemError, ValueError): # not"
] |
[
"the files. The asset file will place the variant files",
"Apache License for the specific # language governing permissions and",
"defaults to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This",
"will enable consumers to defer loading and processing of the",
"is \" \"added to a composition. If unspecified, will be",
"import print_function from pxr import Tf, Kind, Sdf, Usd #",
"with Pixar # convention) # - allow variant names to",
"OF ANY # KIND, either express or implied. See the",
"multiple kinds of files (e.g. shading.usd over geom.usd) # -",
"and replaced with: # # 6. Trademarks. This License does",
"it a payload # and other proper USD trappings -",
"the Apache License, Version 2.0 (the \"Apache License\") # with",
"convention. But always having a class associated with each asset",
"'%s' is not a valid model kind, which must be",
"WARRANTIES OR CONDITIONS OF ANY # KIND, either express or",
"Can be elided \" \"if only one file is supplied\")",
"Sdf, Usd # ToDo: # - handle multiple variantSets #",
"for the specific # language governing permissions and limitations under",
"\" If unspecified, defaults to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='',",
"multiple files to reference if we're switching # them with",
"(Breaks with Pixar # convention) # - allow variant names",
"must be a valid identifier. Aborting.\" % assetName) return None",
"a class associated with each asset is # extremely useful",
"to the (installed) assetName.usd file this script creates. \" \"",
"you would expect your Ar asset-resolver plugin \" \"to resolve",
"file without specifiying a # prim path rootPath = Sdf.Path.absoluteRootPath",
"help=\"Model kind, one of: component, group, or assembly\") parser.add_argument( '-v',",
"'--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset to create to modulate variantFiles.",
"file is supplied\") parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier', help=\"The",
"= Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage = Usd.Stage.Open(rootLayer) # Name",
"variantSet. Aborting\") return None if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s'",
"corresponding input file. ''' from __future__ import print_function from pxr",
"now, we only allow multiple files to reference if we're",
"License does not grant permission to use the trade #",
"help=\"The identifier you would expect your Ar asset-resolver plugin \"",
"# KIND, either express or implied. See the Apache License",
"# convention) # - allow variant names to be specified",
"of the Licensor # and its affiliates, except as required",
"and the following modification to it: # Section 6. Trademarks.",
"variantSet that will be constructed to switch between the files.",
"BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either",
"if filesToReference and len(filesToReference) > 1 and not variantSetName: #",
"variantSetName: # For now, we only allow multiple files to",
"it to be in by default varSet.SetVariantSelection(defaultVariantSelection) return stage if",
"the state we want it to be in by default",
"composed onto a UsdStage. The names of the created variations",
"created variations will be taken directly from the basename of",
"data when composed onto a UsdStage. The names of the",
"\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY #",
"a valid identifier. Aborting.\" % assetName) return None if variantSetName",
"variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK, we're making a variantSet,",
"give it a payload # and other proper USD trappings",
"not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be a valid identifier. Aborting.\"",
"want that to come from referenced files. Make it be",
"stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details #",
"the content of the NOTICE file. # # You may",
"NOTICE file. # # You may obtain a copy of",
"distributed under the Apache License with the above modification is",
"distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS",
"resulting file without specifiying a # prim path rootPath =",
"file this script creates. \" \" If unspecified, defaults to",
"variant we # just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now",
"create to modulate variantFiles. Can be elided \" \"if only",
"# The other, more plausible edge case: we're just wrapping",
"a payload # and other proper USD trappings - no",
"# See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier",
"not necessary for a valid asset, and the class-naming is",
"wrapping # some other file (e.g. alembic) in order to",
"it a type, since we # want that to come",
"os variantName = os.path.splitext(os.path.basename(variantFile))[0] # If we didn't specify a",
"names # - Compute and present (per-variant) UsdGeomModelAPI.extentsHint # -",
"between the files. The asset file will place the variant",
"KIND, either express or implied. See the Apache License for",
"Apache License, Version 2.0 (the \"Apache License\") # with the",
"specifiable? (Breaks with Pixar # convention) # - allow variant",
"of:\" % kind) print(Kind.Registry.GetAllKinds()) return None # Create the root",
"metavar='kind', help=\"Model kind, one of: component, group, or assembly\") parser.add_argument(",
"For now, we only allow multiple files to reference if",
"a top-level, referenceable asset USD file from one or more",
"# ToDo: # - handle multiple variantSets # - layer",
"a UsdStage. The names of the created variations will be",
"- handle multiple variantSets # - layer multiple kinds of",
"# make internal payload arcs (bug #119960) print(\"Cannot create multiple-file-reference",
"to give it a payload # and other proper USD",
"assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This variant will",
"in filesToReference: import os variantName = os.path.splitext(os.path.basename(variantFile))[0] # If we",
"when the asset is \" \"added to a composition. If",
"Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is not a valid model kind,",
"assets of the same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if",
"% variantSetName) return None if filesToReference and len(filesToReference) > 1",
"not variantSetName: # The other, more plausible edge case: we're",
"# - layer multiple kinds of files (e.g. shading.usd over",
"\"added to a composition. If unspecified, will be the variant",
"handle multiple variantSets # - layer multiple kinds of files",
"are going to vary the payload # in each variant",
"import os variantName = os.path.splitext(os.path.basename(variantFile))[0] # If we didn't specify",
"more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add a",
"Apache License with the above modification is # distributed on",
"names of the created variations will be taken directly from",
"variantFiles. Can be elided \" \"if only one file is",
"each variant varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference: import",
"use this file except in # compliance with the Apache",
"None if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is not a",
"Make it be the \"default prim\" # so that we",
"Licensed under the Apache License, Version 2.0 (the \"Apache License\")",
"help=\"Variantset to create to modulate variantFiles. Can be elided \"",
"argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store',",
"print(\"kind '%s' is not a valid model kind, which must",
"their corresponding input file. ''' from __future__ import print_function from",
"the NOTICE file. # # You may obtain a copy",
"shading.usd over geom.usd) # - allow output filename to be",
"all edits \"go inside\" the variant we # just created.",
"kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage: stage.GetRootLayer().Save() exit(0) else: exit(1)",
"with the following modification; you may not use this file",
"of the NOTICE file. # # You may obtain a",
"the Apache License and the following modification to it: #",
"# - allow output filename to be independently specifiable? (Breaks",
"prim\" # so that we can reference the resulting file",
"the root file for the stage, and make it ASCII",
"Compute and present (per-variant) UsdGeomModelAPI.extentsHint # - Compute and author",
"switch between the files. The asset file will place the",
"place the variant files behind a \"payload\", which will enable",
"Pixar # # Licensed under the Apache License, Version 2.0",
"http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName)",
"a variantSet. We can relax this restriction when we can",
"# Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be a",
"onto a UsdStage. The names of the created variations will",
"with Section 4(c) of # the License and to reproduce",
"files, each of which can contain arbitrary scene description. When",
"variant names to be specified independently of variant file names",
"fileName) # Add a class named after the asset, and",
"class associated with each asset is # extremely useful for",
"files behind a \"payload\", which will enable consumers to defer",
"When supplying multiple files, one must also provide the name",
"script creates. \" \" If unspecified, defaults to assetName.usd\") parser.add_argument(",
"kind, which must be one of:\" % kind) print(Kind.Registry.GetAllKinds()) return",
"return None if variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must",
"6. Trademarks. is deleted and replaced with: # # 6.",
"payload arcs (bug #119960) print(\"Cannot create multiple-file-reference without a variantSet.",
"case: we're just wrapping # some other file (e.g. alembic)",
"would expect your Ar asset-resolver plugin \" \"to resolve to",
"parser.error(\"No assetName specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet,",
"of variant file names # - Compute and present (per-variant)",
"+ \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage =",
"parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind', help=\"Model",
"trade # names, trademarks, service marks, or product names of",
"of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"metavar='defaultVariantSelection', help=\"This variant will be selected by default when the",
"variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be a valid",
"# and other proper USD trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0]))",
"from pxr import Tf, Kind, Sdf, Usd # ToDo: #",
"the name for a variantSet that will be constructed to",
"from referenced files. Make it be the \"default prim\" #",
"we are going to vary the payload # in each",
"elif len(filesToReference) == 1 and not variantSetName: # The other,",
"trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK, we're",
"# OK, we're making a variantSet, and we are going",
"class-naming is a Pixar # convention. But always having a",
"created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the variantSet into",
"model kind, which must be one of:\" % kind) print(Kind.Registry.GetAllKinds())",
"that will be constructed to switch between the files. The",
"it: # Section 6. Trademarks. is deleted and replaced with:",
"file will place the variant files behind a \"payload\", which",
"from the basename of their corresponding input file. ''' from",
"classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: # weird edge",
"multiple variantSets # - layer multiple kinds of files (e.g.",
"Aborting\") return None if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is",
"print(\"variantSetName '%s' must be a valid identifier. Aborting.\" % variantSetName)",
"the variantSet into the state we want it to be",
"# 6. Trademarks. This License does not grant permission to",
"\"to resolve to the (installed) assetName.usd file this script creates.",
"name for a variantSet that will be constructed to switch",
"the asset. Don't give it a type, since we #",
"a variantSet. Aborting\") return None if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind",
"asset, and make the asset inherit from it. # This",
"variantSets # - layer multiple kinds of files (e.g. shading.usd",
"'variant' files, each of which can contain arbitrary scene description.",
"behind a \"payload\", which will enable consumers to defer loading",
"action='store', metavar='kind', help=\"Model kind, one of: component, group, or assembly\")",
"not args.assetName or args.assetName == '': parser.error(\"No assetName specified\") stage",
"governing permissions and limitations under the Apache License. # '''",
"output filename to be independently specifiable? (Breaks with Pixar #",
"# in each variant varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile in",
"We need some nicer sugar for this. fileName = assetName",
"vary the payload # in each variant varSet = modelRootPrim.GetVariantSet(variantSetName)",
"default when the asset is \" \"added to a composition.",
"can contain arbitrary scene description. When supplying multiple files, one",
"to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This variant",
"files. Make it be the \"default prim\" # so that",
"to defer loading and processing of the data when composed",
"just wrapping # some other file (e.g. alembic) in order",
"is # distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES",
"present (per-variant) UsdGeomModelAPI.extentsHint # - Compute and author UsdModelAPI::SetPayloadAssetDependencies() def",
"we only allow multiple files to reference if we're switching",
"description. When supplying multiple files, one must also provide the",
"# Copyright 2016 Pixar # # Licensed under the Apache",
"when composed onto a UsdStage. The names of the created",
"variantSet. We can relax this restriction when we can #",
"supplied\") parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier', help=\"The identifier you",
"help=\"This variant will be selected by default when the asset",
"selected by default when the asset is \" \"added to",
"path rootPath = Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI =",
"asset, and the class-naming is a Pixar # convention. But",
"except as required to comply with Section 4(c) of #",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"its affiliates, except as required to comply with Section 4(c)",
"root prim after the asset. Don't give it a type,",
"filesToReference: import os variantName = os.path.splitext(os.path.basename(variantFile))[0] # If we didn't",
"License and the following modification to it: # Section 6.",
"file. # # You may obtain a copy of the",
"= os.path.splitext(os.path.basename(variantFile))[0] # If we didn't specify a default selection,",
"it be the \"default prim\" # so that we can",
"unspecified, defaults to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection',",
"default selection, choose the first one if not defaultVariantSelection: defaultVariantSelection",
"If unspecified, defaults to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store',",
"in each variant varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference:",
"or agreed to in writing, software # distributed under the",
"argparse, os, sys descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr)",
"kind, one of: component, group, or assembly\") parser.add_argument( '-v', '--variantSet',",
"required by applicable law or agreed to in writing, software",
"be independently specifiable? (Breaks with Pixar # convention) # -",
"(e.g. alembic) in order to give it a payload #",
"# distributed on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR",
"may not use this file except in # compliance with",
"copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"Don't give it a type, since we # want that",
"internal payload arcs (bug #119960) print(\"Cannot create multiple-file-reference without a",
"without specifiying a # prim path rootPath = Sdf.Path.absoluteRootPath modelRootPrim",
"If we didn't specify a default selection, choose the first",
"a type, since we # want that to come from",
"identifier you would expect your Ar asset-resolver plugin \" \"to",
"only one file is supplied\") parser.add_argument( '-i', '--identifier', default='', action='store',",
"Ar asset-resolver plugin \" \"to resolve to the (installed) assetName.usd",
"one file is supplied\") parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier',",
"filename to be independently specifiable? (Breaks with Pixar # convention)",
"not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is not a valid model",
"varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context object makes all edits \"go",
"just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the variantSet",
"None if variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be",
"4(c) of # the License and to reproduce the content",
"extremely useful for non-destructively editing many referenced or # instanced",
"makes all edits \"go inside\" the variant we # just",
"asset-resolver plugin \" \"to resolve to the (installed) assetName.usd file",
"Apache License and the following modification to it: # Section",
"necessary for a valid asset, and the class-naming is a",
"from it. # This is not necessary for a valid",
"with each asset is # extremely useful for non-destructively editing",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express",
"of their corresponding input file. ''' from __future__ import print_function",
"if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be a valid identifier.",
"to reproduce the content of the NOTICE file. # #",
"1 and not variantSetName: # The other, more plausible edge",
"by default varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__ == \"__main__\": import",
"except in # compliance with the Apache License and the",
"action='store', metavar='defaultVariantSelection', help=\"This variant will be selected by default when",
"USD trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK,",
"# - allow variant names to be specified independently of",
"on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add a class",
"not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be a valid identifier. Aborting.\"",
"identifier. Aborting.\" % variantSetName) return None if filesToReference and len(filesToReference)",
"and its affiliates, except as required to comply with Section",
"defaultVariantSelection=None): # Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be",
"input file. ''' from __future__ import print_function from pxr import",
"varSet.SetVariantSelection(variantName) # The context object makes all edits \"go inside\"",
"filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s'",
"the asset is \" \"added to a composition. If unspecified,",
"it ASCII text. # We need some nicer sugar for",
"arcs (bug #119960) print(\"Cannot create multiple-file-reference without a variantSet. Aborting\")",
"# some other file (e.g. alembic) in order to give",
"if not defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The",
"so that we can reference the resulting file without specifiying",
"choose the first one if not defaultVariantSelection: defaultVariantSelection = variantName",
"and processing of the data when composed onto a UsdStage.",
"agreed to in writing, software # distributed under the Apache",
"which can contain arbitrary scene description. When supplying multiple files,",
"by default when the asset is \" \"added to a",
"# weird edge case... we're done return stage elif len(filesToReference)",
"to a composition. If unspecified, will be the variant for",
"= assetName + \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args = {'format':'usda'})",
"or args.assetName == '': parser.error(\"No assetName specified\") stage = CreateModelStage(args.assetName,",
"of the data when composed onto a UsdStage. The names",
"for the stage, and make it ASCII text. # We",
"text. # We need some nicer sugar for this. fileName",
"or fileName) # Add a class named after the asset,",
"consumers to defer loading and processing of the data when",
"files, one must also provide the name for a variantSet",
"files. The asset file will place the variant files behind",
"following modification; you may not use this file except in",
"specifiying a # prim path rootPath = Sdf.Path.absoluteRootPath modelRootPrim =",
"rootLayer = Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage = Usd.Stage.Open(rootLayer) #",
"variantSet into the state we want it to be in",
"''' from __future__ import print_function from pxr import Tf, Kind,",
"come from referenced files. Make it be the \"default prim\"",
"USD file from one or more 'variant' files, each of",
"a # prim path rootPath = Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName))",
"not grant permission to use the trade # names, trademarks,",
"this script creates. \" \" If unspecified, defaults to assetName.usd\")",
"will be taken directly from the basename of their corresponding",
"UsdStage. The names of the created variations will be taken",
"we can # make internal payload arcs (bug #119960) print(\"Cannot",
"parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind',",
"# Create the root file for the stage, and make",
"the variant files behind a \"payload\", which will enable consumers",
"to it: # Section 6. Trademarks. is deleted and replaced",
"after the asset. Don't give it a type, since we",
"restriction when we can # make internal payload arcs (bug",
"if __name__ == \"__main__\": import argparse, os, sys descr =",
"\"Apache License\") # with the following modification; you may not",
"other proper USD trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage",
"Pixar # convention. But always having a class associated with",
"the following modification; you may not use this file except",
"resolve to the (installed) assetName.usd file this script creates. \"",
"independently of variant file names # - Compute and present",
"affiliates, except as required to comply with Section 4(c) of",
"having a class associated with each asset is # extremely",
"(installed) assetName.usd file this script creates. \" \" If unspecified,",
"variantSet, and we are going to vary the payload #",
"Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"from __future__ import print_function from pxr import Tf, Kind, Sdf,",
"\".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage = Usd.Stage.Open(rootLayer)",
"License\") # with the following modification; you may not use",
"modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add a class named after the",
"a Pixar # convention. But always having a class associated",
"you may not use this file except in # compliance",
"is not a valid model kind, which must be one",
"= stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: # weird edge case...",
"each asset is # extremely useful for non-destructively editing many",
"be taken directly from the basename of their corresponding input",
"with the Apache License and the following modification to it:",
"But always having a class associated with each asset is",
"= argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component',",
"and make the asset inherit from it. # This is",
"be selected by default when the asset is \" \"added",
"# so that we can reference the resulting file without",
"this restriction when we can # make internal payload arcs",
"one must also provide the name for a variantSet that",
"See the Apache License for the specific # language governing",
"of the created variations will be taken directly from the",
"be elided \" \"if only one file is supplied\") parser.add_argument(",
"defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context object makes",
"deleted and replaced with: # # 6. Trademarks. This License",
"# language governing permissions and limitations under the Apache License.",
"modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on assetInfo modelAPI.SetAssetName(assetName)",
"variantSetName: # The other, more plausible edge case: we're just",
"- no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK, we're making",
"named after the asset, and make the asset inherit from",
"__name__ == \"__main__\": import argparse, os, sys descr = __doc__.strip()",
"OK, we're making a variantSet, and we are going to",
"variant varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference: import os",
"if not args.assetName or args.assetName == '': parser.error(\"No assetName specified\")",
"file except in # compliance with the Apache License and",
"proper USD trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage #",
"prim path rootPath = Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI",
"and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None):",
"\" \"if only one file is supplied\") parser.add_argument( '-i', '--identifier',",
"allow variant names to be specified independently of variant file",
"__future__ import print_function from pxr import Tf, Kind, Sdf, Usd",
"stage = Usd.Stage.Open(rootLayer) # Name the root prim after the",
"Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage = Usd.Stage.Open(rootLayer) # Name the",
"class named after the asset, and make the asset inherit",
"processing of the data when composed onto a UsdStage. The",
"be specified independently of variant file names # - Compute",
"also provide the name for a variantSet that will be",
"a valid asset, and the class-naming is a Pixar #",
"with: # # 6. Trademarks. This License does not grant",
"Apache License. # ''' Creates a top-level, referenceable asset USD",
"CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage: stage.GetRootLayer().Save() exit(0)",
"the Licensor # and its affiliates, except as required to",
"modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK, we're making a variantSet, and",
"License for the specific # language governing permissions and limitations",
"the License and to reproduce the content of the NOTICE",
"multiple-file-reference without a variantSet. Aborting\") return None if not Kind.Registry.IsA(kind,",
"without a variantSet. Aborting\") return None if not Kind.Registry.IsA(kind, Kind.Tokens.model):",
"# The context object makes all edits \"go inside\" the",
"'-i', '--identifier', default='', action='store', metavar='identifier', help=\"The identifier you would expect",
"law or agreed to in writing, software # distributed under",
"variations will be taken directly from the basename of their",
"of files (e.g. shading.usd over geom.usd) # - allow output",
"specify a default selection, choose the first one if not",
"\"default prim\" # so that we can reference the resulting",
"of which can contain arbitrary scene description. When supplying multiple",
"Add a class named after the asset, and make the",
"of the same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not",
"limitations under the Apache License. # ''' Creates a top-level,",
"the above modification is # distributed on an \"AS IS\"",
"we can reference the resulting file without specifiying a #",
"- layer multiple kinds of files (e.g. shading.usd over geom.usd)",
"on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF",
"reference if we're switching # them with a variantSet. We",
"the Apache License for the specific # language governing permissions",
"not filesToReference: # weird edge case... we're done return stage",
"under the Apache License. # ''' Creates a top-level, referenceable",
"the trade # names, trademarks, service marks, or product names",
"a default selection, choose the first one if not defaultVariantSelection:",
"# extremely useful for non-destructively editing many referenced or #",
"creates. \" \" If unspecified, defaults to assetName.usd\") parser.add_argument( '-d',",
"stage, and make it ASCII text. # We need some",
"the specific # language governing permissions and limitations under the",
"# # 6. Trademarks. This License does not grant permission",
"first one if not defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName)",
"args = {'format':'usda'}) stage = Usd.Stage.Open(rootLayer) # Name the root",
"return None # Create the root file for the stage,",
"must be a valid identifier. Aborting.\" % variantSetName) return None",
"modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more",
"selection, choose the first one if not defaultVariantSelection: defaultVariantSelection =",
"- Compute and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None,",
"asset is # extremely useful for non-destructively editing many referenced",
"Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be a valid",
"#119960) print(\"Cannot create multiple-file-reference without a variantSet. Aborting\") return None",
"more 'variant' files, each of which can contain arbitrary scene",
"we didn't specify a default selection, choose the first one",
"assetName.usd file this script creates. \" \" If unspecified, defaults",
"ASCII text. # We need some nicer sugar for this.",
"your Ar asset-resolver plugin \" \"to resolve to the (installed)",
"metavar='variantSet', help=\"Variantset to create to modulate variantFiles. Can be elided",
"for this. fileName = assetName + \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName,",
"loading and processing of the data when composed onto a",
"a copy of the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0",
"'%s' must be a valid identifier. Aborting.\" % variantSetName) return",
"and make it ASCII text. # We need some nicer",
"it. # This is not necessary for a valid asset,",
"make the asset inherit from it. # This is not",
"Name the root prim after the asset. Don't give it",
"permissions and limitations under the Apache License. # ''' Creates",
"supplying multiple files, one must also provide the name for",
"\"if only one file is supplied\") parser.add_argument( '-i', '--identifier', default='',",
"in order to give it a payload # and other",
"variantName = os.path.splitext(os.path.basename(variantFile))[0] # If we didn't specify a default",
"Licensor # and its affiliates, except as required to comply",
"'--identifier', default='', action='store', metavar='identifier', help=\"The identifier you would expect your",
"valid model kind, which must be one of:\" % kind)",
"ToDo: # - handle multiple variantSets # - layer multiple",
"Aborting.\" % assetName) return None if variantSetName and not Tf.IsValidIdentifier(variantSetName):",
"make internal payload arcs (bug #119960) print(\"Cannot create multiple-file-reference without",
"Usd.Stage.Open(rootLayer) # Name the root prim after the asset. Don't",
"referenceable asset USD file from one or more 'variant' files,",
"order to give it a payload # and other proper",
"You may obtain a copy of the Apache License at",
"product names of the Licensor # and its affiliates, except",
"the first one if not defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName)",
"be the variant for \" \"'variantFile1'\") args = parser.parse_args() if",
"\" \"'variantFile1'\") args = parser.parse_args() if not args.assetName or args.assetName",
"'': parser.error(\"No assetName specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles,",
"default='', action='store', metavar='identifier', help=\"The identifier you would expect your Ar",
"Version 2.0 (the \"Apache License\") # with the following modification;",
"Aborting.\" % variantSetName) return None if filesToReference and len(filesToReference) >",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind', help=\"Model kind, one of:",
"after the asset, and make the asset inherit from it.",
"args.assetName == '': parser.error(\"No assetName specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier,",
"provide the name for a variantSet that will be constructed",
"allow output filename to be independently specifiable? (Breaks with Pixar",
"# # Licensed under the Apache License, Version 2.0 (the",
"which must be one of:\" % kind) print(Kind.Registry.GetAllKinds()) return None",
"- Compute and present (per-variant) UsdGeomModelAPI.extentsHint # - Compute and",
"args = parser.parse_args() if not args.assetName or args.assetName == '':",
"Section 6. Trademarks. is deleted and replaced with: # #",
"valid asset, and the class-naming is a Pixar # convention.",
"return stage elif len(filesToReference) == 1 and not variantSetName: #",
"2016 Pixar # # Licensed under the Apache License, Version",
"# want that to come from referenced files. Make it",
"author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): #",
"more plausible edge case: we're just wrapping # some other",
"inherit from it. # This is not necessary for a",
"composition. If unspecified, will be the variant for \" \"'variantFile1'\")",
"# Now put the variantSet into the state we want",
"nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind', help=\"Model kind, one",
"instanced assets of the same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath())",
"pxr import Tf, Kind, Sdf, Usd # ToDo: # -",
"the Apache License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"permission to use the trade # names, trademarks, service marks,",
"OR CONDITIONS OF ANY # KIND, either express or implied.",
"nicer sugar for this. fileName = assetName + \".usd\" rootLayer",
"\" \"to resolve to the (installed) assetName.usd file this script",
"Kind, Sdf, Usd # ToDo: # - handle multiple variantSets",
"and limitations under the Apache License. # ''' Creates a",
"== \"__main__\": import argparse, os, sys descr = __doc__.strip() parser",
"'--kind', default='component', action='store', metavar='kind', help=\"Model kind, one of: component, group,",
"Now put the variantSet into the state we want it",
"= Usd.Stage.Open(rootLayer) # Name the root prim after the asset.",
"\"go inside\" the variant we # just created. with varSet.GetVariantEditContext():",
"over geom.usd) # - allow output filename to be independently",
"the Apache License with the above modification is # distributed",
"''' Creates a top-level, referenceable asset USD file from one",
"above modification is # distributed on an \"AS IS\" BASIS,",
"assetName specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection)",
"stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage:",
"to comply with Section 4(c) of # the License and",
"os.path.splitext(os.path.basename(variantFile))[0] # If we didn't specify a default selection, choose",
"description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind',",
"writing, software # distributed under the Apache License with the",
"trademarks, service marks, or product names of the Licensor #",
"is # extremely useful for non-destructively editing many referenced or",
"one of: component, group, or assembly\") parser.add_argument( '-v', '--variantSet', default='',",
"for a valid asset, and the class-naming is a Pixar",
"__doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k',",
"assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions.... if not Tf.IsValidIdentifier(assetName):",
"print(\"Cannot create multiple-file-reference without a variantSet. Aborting\") return None if",
"edits \"go inside\" the variant we # just created. with",
"state we want it to be in by default varSet.SetVariantSelection(defaultVariantSelection)",
"edge case... we're done return stage elif len(filesToReference) == 1",
"kinds of files (e.g. shading.usd over geom.usd) # - allow",
"going to vary the payload # in each variant varSet",
"under the Apache License with the above modification is #",
"the Apache License. # ''' Creates a top-level, referenceable asset",
"from one or more 'variant' files, each of which can",
"modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add a class named after",
"# instanced assets of the same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName))",
"# Section 6. Trademarks. is deleted and replaced with: #",
"# distributed under the Apache License with the above modification",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"# - Compute and present (per-variant) UsdGeomModelAPI.extentsHint # - Compute",
"to be independently specifiable? (Breaks with Pixar # convention) #",
"assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add a class named",
"we're done return stage elif len(filesToReference) == 1 and not",
"other, more plausible edge case: we're just wrapping # some",
"filesToReference and len(filesToReference) > 1 and not variantSetName: # For",
"marks, or product names of the Licensor # and its",
"filesToReference: # weird edge case... we're done return stage elif",
"a \"payload\", which will enable consumers to defer loading and",
"# If we didn't specify a default selection, choose the",
"Tf, Kind, Sdf, Usd # ToDo: # - handle multiple",
"# prim path rootPath = Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim)",
"modulate variantFiles. Can be elided \" \"if only one file",
"the stage, and make it ASCII text. # We need",
"not defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context",
"may obtain a copy of the Apache License at #",
"arbitrary scene description. When supplying multiple files, one must also",
"varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the variantSet into the state",
"must be one of:\" % kind) print(Kind.Registry.GetAllKinds()) return None #",
"Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be a valid identifier. Aborting.\" %",
"to come from referenced files. Make it be the \"default",
"License. # ''' Creates a top-level, referenceable asset USD file",
"# Licensed under the Apache License, Version 2.0 (the \"Apache",
"asset USD file from one or more 'variant' files, each",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"as required to comply with Section 4(c) of # the",
"other file (e.g. alembic) in order to give it a",
"default varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__ == \"__main__\": import argparse,",
"# We need some nicer sugar for this. fileName =",
"modification is # distributed on an \"AS IS\" BASIS, WITHOUT",
"for non-destructively editing many referenced or # instanced assets of",
"ANY # KIND, either express or implied. See the Apache",
"License with the above modification is # distributed on an",
"assetName) return None if variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s'",
"the asset, and make the asset inherit from it. #",
"default='', action='store', metavar='variantSet', help=\"Variantset to create to modulate variantFiles. Can",
"default='', action='store', metavar='defaultVariantSelection', help=\"This variant will be selected by default",
"will place the variant files behind a \"payload\", which will",
"Trademarks. This License does not grant permission to use the",
"independently specifiable? (Breaks with Pixar # convention) # - allow",
"CONDITIONS OF ANY # KIND, either express or implied. See",
"and not variantSetName: # For now, we only allow multiple",
"one if not defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) #",
"is deleted and replaced with: # # 6. Trademarks. This",
"grant permission to use the trade # names, trademarks, service",
"obtain a copy of the Apache License at # #",
"to vary the payload # in each variant varSet =",
"put the variantSet into the state we want it to",
"specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if",
"weird edge case... we're done return stage elif len(filesToReference) ==",
"The asset file will place the variant files behind a",
"stage # OK, we're making a variantSet, and we are",
"parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier', help=\"The identifier you would",
"print_function from pxr import Tf, Kind, Sdf, Usd # ToDo:",
"defer loading and processing of the data when composed onto",
"layer multiple kinds of files (e.g. shading.usd over geom.usd) #",
"return stage # OK, we're making a variantSet, and we",
"not use this file except in # compliance with the",
"variantSetName=None, defaultVariantSelection=None): # Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must",
"The other, more plausible edge case: we're just wrapping #",
"and other proper USD trappings - no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return",
"will be selected by default when the asset is \"",
"the asset inherit from it. # This is not necessary",
"# # Unless required by applicable law or agreed to",
"can relax this restriction when we can # make internal",
"modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: # weird edge case... we're done",
"file for the stage, and make it ASCII text. #",
"= __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+') parser.add_argument(",
"return stage if __name__ == \"__main__\": import argparse, os, sys",
"valid identifier. Aborting.\" % variantSetName) return None if filesToReference and",
"a valid identifier. Aborting.\" % variantSetName) return None if filesToReference",
"Pixar # convention) # - allow variant names to be",
"if we're switching # them with a variantSet. We can",
"# with the following modification; you may not use this",
"(the \"Apache License\") # with the following modification; you may",
"with the above modification is # distributed on an \"AS",
"We can relax this restriction when we can # make",
"sugar for this. fileName = assetName + \".usd\" rootLayer =",
"License, Version 2.0 (the \"Apache License\") # with the following",
"= Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind)",
"the basename of their corresponding input file. ''' from __future__",
"this. fileName = assetName + \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args",
"to use the trade # names, trademarks, service marks, or",
"for a variantSet that will be constructed to switch between",
"metavar='identifier', help=\"The identifier you would expect your Ar asset-resolver plugin",
"Copyright 2016 Pixar # # Licensed under the Apache License,",
"be one of:\" % kind) print(Kind.Registry.GetAllKinds()) return None # Create",
"to in writing, software # distributed under the Apache License",
"== 1 and not variantSetName: # The other, more plausible",
"modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See",
"Create the root file for the stage, and make it",
"a variantSet, and we are going to vary the payload",
"'-v', '--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset to create to modulate",
"we # just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put",
"None if filesToReference and len(filesToReference) > 1 and not variantSetName:",
"is a Pixar # convention. But always having a class",
"useful for non-destructively editing many referenced or # instanced assets",
"the payload # in each variant varSet = modelRootPrim.GetVariantSet(variantSetName) for",
"Usd # ToDo: # - handle multiple variantSets # -",
"top-level, referenceable asset USD file from one or more 'variant'",
"variant file names # - Compute and present (per-variant) UsdGeomModelAPI.extentsHint",
"give it a type, since we # want that to",
"modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference: import os variantName = os.path.splitext(os.path.basename(variantFile))[0]",
"we want it to be in by default varSet.SetVariantSelection(defaultVariantSelection) return",
"import argparse, os, sys descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),",
"is supplied\") parser.add_argument( '-i', '--identifier', default='', action='store', metavar='identifier', help=\"The identifier",
"not variantSetName: # For now, we only allow multiple files",
"some nicer sugar for this. fileName = assetName + \".usd\"",
"under the Apache License, Version 2.0 (the \"Apache License\") #",
"must also provide the name for a variantSet that will",
"payload # and other proper USD trappings - no variants",
"by applicable law or agreed to in writing, software #",
"to be specified independently of variant file names # -",
"# For now, we only allow multiple files to reference",
"the root prim after the asset. Don't give it a",
"the following modification to it: # Section 6. Trademarks. is",
"will be constructed to switch between the files. The asset",
"CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions.... if not",
"following modification to it: # Section 6. Trademarks. is deleted",
"relax this restriction when we can # make internal payload",
"type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: # weird",
"variant will be selected by default when the asset is",
"file from one or more 'variant' files, each of which",
"# This is not necessary for a valid asset, and",
"default='component', action='store', metavar='kind', help=\"Model kind, one of: component, group, or",
"The context object makes all edits \"go inside\" the variant",
"and the class-naming is a Pixar # convention. But always",
"this file except in # compliance with the Apache License",
"be in by default varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__ ==",
"(e.g. shading.usd over geom.usd) # - allow output filename to",
"scene description. When supplying multiple files, one must also provide",
"rootPath = Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim)",
"component, group, or assembly\") parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet',",
"make it ASCII text. # We need some nicer sugar",
"'-k', '--kind', default='component', action='store', metavar='kind', help=\"Model kind, one of: component,",
"multiple files, one must also provide the name for a",
"of: component, group, or assembly\") parser.add_argument( '-v', '--variantSet', default='', action='store',",
"The names of the created variations will be taken directly",
"editing many referenced or # instanced assets of the same",
"making a variantSet, and we are going to vary the",
"Tf.IsValidIdentifier(assetName): print(\"assetName '%s' must be a valid identifier. Aborting.\" %",
"software # distributed under the Apache License with the above",
"be a valid identifier. Aborting.\" % variantSetName) return None if",
"Kind.Tokens.model): print(\"kind '%s' is not a valid model kind, which",
"stage elif len(filesToReference) == 1 and not variantSetName: # The",
"a variantSet that will be constructed to switch between the",
"payload # in each variant varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile",
"asset file will place the variant files behind a \"payload\",",
"object makes all edits \"go inside\" the variant we #",
"modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the variantSet into the state we",
"the class-naming is a Pixar # convention. But always having",
"> 1 and not variantSetName: # For now, we only",
"non-destructively editing many referenced or # instanced assets of the",
"basename of their corresponding input file. ''' from __future__ import",
"to reference if we're switching # them with a variantSet.",
"for variantFile in filesToReference: import os variantName = os.path.splitext(os.path.basename(variantFile))[0] #",
"print(\"assetName '%s' must be a valid identifier. Aborting.\" % assetName)",
"os, sys descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName')",
"varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__ == \"__main__\": import argparse, os,",
"or # instanced assets of the same type. classPrim =",
"the (installed) assetName.usd file this script creates. \" \" If",
"file names # - Compute and present (per-variant) UsdGeomModelAPI.extentsHint #",
"stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: # weird edge case... we're",
"'-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This variant will be selected",
"alembic) in order to give it a payload # and",
"asset. Don't give it a type, since we # want",
"to be in by default varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__",
"and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be a valid identifier.",
"Unless required by applicable law or agreed to in writing,",
"the data when composed onto a UsdStage. The names of",
"one or more 'variant' files, each of which can contain",
"the resulting file without specifiying a # prim path rootPath",
"case... we're done return stage elif len(filesToReference) == 1 and",
"defaultVariantSelection: defaultVariantSelection = variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context object",
"a valid model kind, which must be one of:\" %",
"express or implied. See the Apache License for the specific",
"either express or implied. See the Apache License for the",
"each of which can contain arbitrary scene description. When supplying",
"asset inherit from it. # This is not necessary for",
"is not necessary for a valid asset, and the class-naming",
"Trademarks. is deleted and replaced with: # # 6. Trademarks.",
"and present (per-variant) UsdGeomModelAPI.extentsHint # - Compute and author UsdModelAPI::SetPayloadAssetDependencies()",
"applicable law or agreed to in writing, software # distributed",
"stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for",
"len(filesToReference) == 1 and not variantSetName: # The other, more",
"for \" \"'variantFile1'\") args = parser.parse_args() if not args.assetName or",
"variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context object makes all edits",
"comply with Section 4(c) of # the License and to",
"we're just wrapping # some other file (e.g. alembic) in",
"UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions....",
"Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on assetInfo",
"root file for the stage, and make it ASCII text.",
"for more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) # Add",
"{'format':'usda'}) stage = Usd.Stage.Open(rootLayer) # Name the root prim after",
"file. ''' from __future__ import print_function from pxr import Tf,",
"and we are going to vary the payload # in",
"sys descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles',",
"we're making a variantSet, and we are going to vary",
"fileName = assetName + \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args =",
"replaced with: # # 6. Trademarks. This License does not",
"(bug #119960) print(\"Cannot create multiple-file-reference without a variantSet. Aborting\") return",
"be a valid identifier. Aborting.\" % assetName) return None if",
"Creates a top-level, referenceable asset USD file from one or",
"elided \" \"if only one file is supplied\") parser.add_argument( '-i',",
"prim after the asset. Don't give it a type, since",
"files (e.g. shading.usd over geom.usd) # - allow output filename",
"compliance with the Apache License and the following modification to",
"we're switching # them with a variantSet. We can relax",
"# - handle multiple variantSets # - layer multiple kinds",
"inside\" the variant we # just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile))",
"% kind) print(Kind.Registry.GetAllKinds()) return None # Create the root file",
"variantSetName) return None if filesToReference and len(filesToReference) > 1 and",
"the created variations will be taken directly from the basename",
"the same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference:",
"parser.parse_args() if not args.assetName or args.assetName == '': parser.error(\"No assetName",
"# # You may obtain a copy of the Apache",
"action='store', metavar='variantSet', help=\"Variantset to create to modulate variantFiles. Can be",
"None # Create the root file for the stage, and",
"# for more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or fileName) #",
"contain arbitrary scene description. When supplying multiple files, one must",
"(per-variant) UsdGeomModelAPI.extentsHint # - Compute and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName,",
"switching # them with a variantSet. We can relax this",
"taken directly from the basename of their corresponding input file.",
"# ''' Creates a top-level, referenceable asset USD file from",
"Compute and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None,",
"expect your Ar asset-resolver plugin \" \"to resolve to the",
"the variant for \" \"'variantFile1'\") args = parser.parse_args() if not",
"action='store', metavar='identifier', help=\"The identifier you would expect your Ar asset-resolver",
"or product names of the Licensor # and its affiliates,",
"be constructed to switch between the files. The asset file",
"in writing, software # distributed under the Apache License with",
"since we # want that to come from referenced files.",
"args.assetName or args.assetName == '': parser.error(\"No assetName specified\") stage =",
"constructed to switch between the files. The asset file will",
"modification to it: # Section 6. Trademarks. is deleted and",
"identifier. Aborting.\" % assetName) return None if variantSetName and not",
"import Tf, Kind, Sdf, Usd # ToDo: # - handle",
"variant files behind a \"payload\", which will enable consumers to",
"allow multiple files to reference if we're switching # them",
"kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions.... if not Tf.IsValidIdentifier(assetName): print(\"assetName",
"not a valid model kind, which must be one of:\"",
"parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset to create to",
"parser.add_argument( '-d', '--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This variant will be",
"no variants modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(filesToReference[0])) return stage # OK, we're making a",
"plugin \" \"to resolve to the (installed) assetName.usd file this",
"# compliance with the Apache License and the following modification",
"file (e.g. alembic) in order to give it a payload",
"% assetName) return None if variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName",
"- allow output filename to be independently specifiable? (Breaks with",
"This License does not grant permission to use the trade",
"be the \"default prim\" # so that we can reference",
"Sdf.Path.absoluteRootPath modelRootPrim = stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) #",
"in by default varSet.SetVariantSelection(defaultVariantSelection) return stage if __name__ == \"__main__\":",
"service marks, or product names of the Licensor # and",
"#!/pxrpythonsubst # # Copyright 2016 Pixar # # Licensed under",
"return None if filesToReference and len(filesToReference) > 1 and not",
"with a variantSet. We can relax this restriction when we",
"names, trademarks, service marks, or product names of the Licensor",
"\"payload\", which will enable consumers to defer loading and processing",
"# - Compute and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component,",
"This is not necessary for a valid asset, and the",
"which will enable consumers to defer loading and processing of",
"return None if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is not",
"variantFile in filesToReference: import os variantName = os.path.splitext(os.path.basename(variantFile))[0] # If",
"# just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the",
"that we can reference the resulting file without specifiying a",
"stage if __name__ == \"__main__\": import argparse, os, sys descr",
"= {'format':'usda'}) stage = Usd.Stage.Open(rootLayer) # Name the root prim",
"a composition. If unspecified, will be the variant for \"",
"\"'variantFile1'\") args = parser.parse_args() if not args.assetName or args.assetName ==",
"# You may obtain a copy of the Apache License",
"if variantSetName and not Tf.IsValidIdentifier(variantSetName): print(\"variantSetName '%s' must be a",
"and len(filesToReference) > 1 and not variantSetName: # For now,",
"# Name the root prim after the asset. Don't give",
"unspecified, will be the variant for \" \"'variantFile1'\") args =",
"descr = __doc__.strip() parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), description=descr) parser.add_argument('assetName') parser.add_argument('variantFiles', nargs='+')",
"specified independently of variant file names # - Compute and",
"we # want that to come from referenced files. Make",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"len(filesToReference) > 1 and not variantSetName: # For now, we",
"\" \" If unspecified, defaults to assetName.usd\") parser.add_argument( '-d', '--defaultVariantSelection',",
"of # the License and to reproduce the content of",
"variant for \" \"'variantFile1'\") args = parser.parse_args() if not args.assetName",
"can reference the resulting file without specifiying a # prim",
"or more 'variant' files, each of which can contain arbitrary",
"print(Kind.Registry.GetAllKinds()) return None # Create the root file for the",
"names of the Licensor # and its affiliates, except as",
"if not filesToReference: # weird edge case... we're done return",
"only allow multiple files to reference if we're switching #",
"License and to reproduce the content of the NOTICE file.",
"didn't specify a default selection, choose the first one if",
"can # make internal payload arcs (bug #119960) print(\"Cannot create",
"= variantName varSet.AddVariant(variantName) varSet.SetVariantSelection(variantName) # The context object makes all",
"and not variantSetName: # The other, more plausible edge case:",
"context object makes all edits \"go inside\" the variant we",
"always having a class associated with each asset is #",
"files to reference if we're switching # them with a",
"# the License and to reproduce the content of the",
"language governing permissions and limitations under the Apache License. #",
"= parser.parse_args() if not args.assetName or args.assetName == '': parser.error(\"No",
"or assembly\") parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset to",
"to switch between the files. The asset file will place",
"Section 4(c) of # the License and to reproduce the",
"into the state we want it to be in by",
"directly from the basename of their corresponding input file. '''",
"one of:\" % kind) print(Kind.Registry.GetAllKinds()) return None # Create the",
"valid identifier. Aborting.\" % assetName) return None if variantSetName and",
"# and its affiliates, except as required to comply with",
"names to be specified independently of variant file names #",
"implied. See the Apache License for the specific # language",
"specific # language governing permissions and limitations under the Apache",
"in # compliance with the Apache License and the following",
"reproduce the content of the NOTICE file. # # You",
"geom.usd) # - allow output filename to be independently specifiable?",
"asset is \" \"added to a composition. If unspecified, will",
"If unspecified, will be the variant for \" \"'variantFile1'\") args",
"or implied. See the Apache License for the specific #",
"assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage: stage.GetRootLayer().Save() exit(0) else:",
"many referenced or # instanced assets of the same type.",
"modification; you may not use this file except in #",
"kind) print(Kind.Registry.GetAllKinds()) return None # Create the root file for",
"associated with each asset is # extremely useful for non-destructively",
"same type. classPrim = stage.CreateClassPrim(rootPath.AppendChild(\"_class_\"+assetName)) modelRootPrim.GetInherits().AddInherit(classPrim.GetPath()) if not filesToReference: #",
"plausible edge case: we're just wrapping # some other file",
"some other file (e.g. alembic) in order to give it",
"varSet = modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference: import os variantName",
"1 and not variantSetName: # For now, we only allow",
"enable consumers to defer loading and processing of the data",
"def CreateModelStage(assetName, assetIdentifier=None, kind=Kind.Tokens.component, filesToReference=None, variantSetName=None, defaultVariantSelection=None): # Preconditions.... if",
"referenced files. Make it be the \"default prim\" # so",
"edge case: we're just wrapping # some other file (e.g.",
"required to comply with Section 4(c) of # the License",
"See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on assetInfo modelAPI.SetAssetName(assetName) modelAPI.SetAssetIdentifier(assetIdentifier or",
"= CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind, filesToReference=args.variantFiles, variantSetName=args.variantSet, defaultVariantSelection=args.defaultVariantSelection) if stage: stage.GetRootLayer().Save()",
"that to come from referenced files. Make it be the",
"# them with a variantSet. We can relax this restriction",
"to modulate variantFiles. Can be elided \" \"if only one",
"parser.add_argument('variantFiles', nargs='+') parser.add_argument( '-k', '--kind', default='component', action='store', metavar='kind', help=\"Model kind,",
"\" \"added to a composition. If unspecified, will be the",
"does not grant permission to use the trade # names,",
"want it to be in by default varSet.SetVariantSelection(defaultVariantSelection) return stage",
"referenced or # instanced assets of the same type. classPrim",
"# # Copyright 2016 Pixar # # Licensed under the",
"assetName + \".usd\" rootLayer = Sdf.Layer.CreateNew(fileName, args = {'format':'usda'}) stage",
"if not Kind.Registry.IsA(kind, Kind.Tokens.model): print(\"kind '%s' is not a valid",
"# Unless required by applicable law or agreed to in",
"reference the resulting file without specifiying a # prim path",
"= stage.DefinePrim(rootPath.AppendChild(assetName)) stage.SetDefaultPrim(modelRootPrim) modelAPI = Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details",
"when we can # make internal payload arcs (bug #119960)",
"the variant we # just created. with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) #",
"'%s' must be a valid identifier. Aborting.\" % assetName) return",
"convention) # - allow variant names to be specified independently",
"# Add a class named after the asset, and make",
"IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND,",
"create multiple-file-reference without a variantSet. Aborting\") return None if not",
"need some nicer sugar for this. fileName = assetName +",
"# names, trademarks, service marks, or product names of the",
"with varSet.GetVariantEditContext(): modelRootPrim.GetPayloads().AddPayload(Sdf.Payload(variantFile)) # Now put the variantSet into the",
"done return stage elif len(filesToReference) == 1 and not variantSetName:",
"a class named after the asset, and make the asset",
"and to reproduce the content of the NOTICE file. #",
"6. Trademarks. This License does not grant permission to use",
"use the trade # names, trademarks, service marks, or product",
"= Usd.ModelAPI(modelRootPrim) modelAPI.SetKind(kind) # See http://openusd.org/docs/api/class_usd_model_a_p_i.html#details # for more on",
"to create to modulate variantFiles. Can be elided \" \"if",
"'--defaultVariantSelection', default='', action='store', metavar='defaultVariantSelection', help=\"This variant will be selected by",
"assembly\") parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset to create",
"- allow variant names to be specified independently of variant",
"will be the variant for \" \"'variantFile1'\") args = parser.parse_args()",
"type, since we # want that to come from referenced",
"the \"default prim\" # so that we can reference the",
"an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"2.0 (the \"Apache License\") # with the following modification; you",
"\"__main__\": import argparse, os, sys descr = __doc__.strip() parser =",
"UsdGeomModelAPI.extentsHint # - Compute and author UsdModelAPI::SetPayloadAssetDependencies() def CreateModelStage(assetName, assetIdentifier=None,",
"group, or assembly\") parser.add_argument( '-v', '--variantSet', default='', action='store', metavar='variantSet', help=\"Variantset",
"== '': parser.error(\"No assetName specified\") stage = CreateModelStage(args.assetName, assetIdentifier=args.identifier, kind=args.kind,",
"= modelRootPrim.GetVariantSet(variantSetName) for variantFile in filesToReference: import os variantName =",
"# convention. But always having a class associated with each",
"content of the NOTICE file. # # You may obtain",
"them with a variantSet. We can relax this restriction when"
] |
[
"def check_time(function): @wraps(function) def measure(*args, **kwargs): start_time = time.time() result",
"'/' + name if not os.path.isfile(path): dir_list.append(name) return dir_list def",
"save_file_name @check_time def init_simul(filename, test_num, cbr_num=50, div_step=1): data = read_data_skeleton(filename)",
"data = read_data_skeleton(filename) # test_num, data = interval_compasation(data, test_num, div_step)",
"model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state)",
"lower_init_cov, upper_init_mean, upper_init_cov) else: print(model, \"is not exist model name\")",
"open(filename, 'r') line = f.readline() wf.write(line) wf.close() return save_file_name @check_time",
"not exist model name\") return flt @check_time def run_ukf(ukf, skeletons,",
"i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean =",
"read_csv(filename): data = [] with open(filename, 'r') as reader: for",
"= get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length = get_save_image_file_name(person_name, pos_mode, model,",
"name if not os.path.isfile(path): dir_list.append(name) return dir_list def scan_dir(dir): dir_list",
"else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state, model):",
"import Skeleton from read_data import * from calibration import Calibration",
"fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for i in range(len(fields)): data.append(float(fields[i])) data",
"= make_folder(folder_name + '/' + plot_mode) return folder_name + '/'",
"velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100):",
"data = np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons = [] for d",
"def measure(*args, **kwargs): start_time = time.time() result = function(*args, **kwargs)",
"dir_list.append(name) return dir_list def scan_dir(dir): dir_list = [] for name",
"not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name",
"pos_mode, model, plot_mode): folder_name = make_folder('result') folder_name = make_folder(folder_name +",
"import wraps import os def check_time(function): @wraps(function) def measure(*args, **kwargs):",
"print(\"test_num:\", end=' ') for i in range(test_num): curr_input = skeletons[i].get_measurement()",
"end=' ') for i in range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input)",
"\"is not exist model name\") return flt @check_time def run_ukf(ukf,",
"dir_list @check_time def merge_skeleton_data(folder_name): save_file_name = folder_name + '.txt' dir_list",
"curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state, data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state)",
"open(save_file_name, 'w') for filename in dir_list: f = open(filename, 'r')",
"model): flt = None if model == 'ukf': flt =",
"save_sk_data_to_csv(folder_name, filename, data): filename = folder_name + filename f =",
"pos_mode, model, 'point') img_name_length = get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D",
"test_num): original_data = [] estimate_data = [] estimate_state = []",
"read_data import * from calibration import Calibration from ukf_filter import",
"obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor,",
"if j == (len(data[i])-1) and k == 2: f.write('\\n') else:",
"+ '/' + name if not os.path.isfile(path): dir_list.append(name) return dir_list",
"make_folder(folder_name + '/' + plot_mode) return folder_name + '/' @check_time",
"skeletons, test_num): original_data = [] estimate_data = [] estimate_state =",
"name if os.path.isfile(path): dir_list.append(path) return dir_list @check_time def merge_skeleton_data(folder_name): save_file_name",
"- start_time}\") return result return measure def get_dir_name(dir): dir_list =",
"for i in range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32, 3)",
"os def check_time(function): @wraps(function) def measure(*args, **kwargs): start_time = time.time()",
"cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename) return",
"folder_name = make_folder(folder_name + '/' + person_name) folder_name = make_folder(folder_name",
"@check_time def merge_skeleton_data(folder_name): save_file_name = folder_name + '.txt' dir_list =",
"range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num) cal_skeletons = [] for",
"@check_time def skeleton_draw(person_name, pos_mode, model, original_data, estimate_data, sleep_t=100): canvas =",
"return flt @check_time def run_ukf(ukf, skeletons, test_num): original_data = []",
"function(*args, **kwargs) end_time = time.time() print(f\"@check_time: {function.__name__} took {end_time -",
"= [] test_num = min(len(skeletons), test_num) print(\"total test is {}\".format(test_num))",
"name in os.listdir(dir): path = dir + '/' + name",
"line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for i in range(len(fields)): data.append(float(fields[i]))",
"os.listdir(dir): path = dir + '/' + name if os.path.isfile(path):",
"save_file_name = folder_name + '.txt' dir_list = scan_dir(folder_name) wf =",
"plot_mode): folder_name = make_folder('result') folder_name = make_folder(folder_name + '/' +",
"= make_folder(folder_name + '/' + model) folder_name = make_folder(folder_name +",
"dir_list.append(path) return dir_list @check_time def merge_skeleton_data(folder_name): save_file_name = folder_name +",
"save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode,",
"model, 'length') img_name_3D = get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data,",
"+ model) return folder_name + '/' def save_sk_data_to_csv(folder_name, filename, data):",
"= read_data_skeleton(filename) # test_num, data = interval_compasation(data, test_num, div_step) test_num",
"+ 'estimate_data.csv') return original_data, estimate_data def get_save_image_file_name(person_name, pos_mode, model, plot_mode):",
"dir + '/' + name if not os.path.isfile(path): dir_list.append(name) return",
"in data: skeletons.append(Skeleton(d)) return skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode, model):",
"**kwargs): start_time = time.time() result = function(*args, **kwargs) end_time =",
"print(model, \"is not exist model name\") return flt @check_time def",
"name\") return flt @check_time def run_ukf(ukf, skeletons, test_num): original_data =",
"velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10,",
"'/' + pos_mode) folder_name = make_folder(folder_name + '/' + model)",
"def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name,",
"f.write('\\n') else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state,",
"cal_skeletons = [] for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration =",
"f.write(str(data[i][j][k])) if j == (len(data[i])-1) and k == 2: f.write('\\n')",
"== 0: print(i, end=' ') print('') return original_data, estimate_data, estimate_state",
"= [] estimate_data = [] estimate_state = [] test_num =",
"@check_time def run_ukf(ukf, skeletons, test_num): original_data = [] estimate_data =",
"return save_file_name @check_time def init_simul(filename, test_num, cbr_num=50, div_step=1): data =",
"estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename): data = [] with",
"for j in range(len(data[i])): for k in range(3): f.write(str(data[i][j][k])) if",
"trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor]",
"import ukf_Filter_Controler from canvas import Canvas from regression import *",
"= fields[len(fields)-1].replace('\\n', '') for i in range(len(fields)): data.append(float(fields[i])) data =",
"import * import time from functools import wraps import os",
"def skeleton_draw(person_name, pos_mode, model, original_data, estimate_data, sleep_t=100): canvas = Canvas()",
"data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons = [] for",
"img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4,",
"data): filename = folder_name + filename f = open(filename, \"w\",",
"from regression import * import time from functools import wraps",
"model, original_data, estimate_data, sleep_t=100): canvas = Canvas() img_name_point = get_save_image_file_name(person_name,",
"if model == 'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov)",
"= make_folder(folder_name + '/' + pos_mode) folder_name = make_folder(folder_name +",
"[] for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean,",
"'/' + plot_mode) return folder_name + '/' @check_time def skeleton_draw(person_name,",
"simulation_ukf(filename, test_num, cbr_num, model): skeletons, lower_init_mean, upper_init_mean, test_num = init_simul(filename,",
"Calibration from ukf_filter import ukf_Filter_Controler from canvas import Canvas from",
"save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def",
"time from functools import wraps import os def check_time(function): @wraps(function)",
"sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6,",
"scan_dir(dir): dir_list = [] for name in os.listdir(dir): path =",
"= interval_compasation(data, test_num, div_step) test_num = min(test_num, len(data)) skeletons =",
"= min(test_num, cbr_num) cal_skeletons = [] for i in range(cbr_num):",
"return result return measure def get_dir_name(dir): dir_list = [] for",
"estimate_state = [] test_num = min(len(skeletons), test_num) print(\"total test is",
"upper_init_cov, model) original_data, estimate_data, estimate_state = run_ukf(flt, skeletons, test_num) return",
"calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename) return skeletons,",
"in range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons =",
"folder_name = make_folder(folder_name + '/' + pos_mode) folder_name = make_folder(folder_name",
"# test_num, data = interval_compasation(data, test_num, div_step) test_num = min(test_num,",
"None if model == 'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean,",
"+ '/' + pos_mode) folder_name = make_folder(folder_name + '/' +",
"pos_mode) folder_name = make_folder(folder_name + '/' + model) return folder_name",
"test_num, cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt =",
"len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0,",
"in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num) cal_skeletons = []",
"j == (len(data[i])-1) and k == 2: f.write('\\n') else: f.write(',')",
"{end_time - start_time}\") return result return measure def get_dir_name(dir): dir_list",
"def simulation_ukf(filename, test_num, cbr_num, model): skeletons, lower_init_mean, upper_init_mean, test_num =",
"canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2,",
"in range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1) and k ==",
"flt = None if model == 'ukf': flt = ukf_Filter_Controler(lower_init_mean,",
"wf.write(line) wf.close() return save_file_name @check_time def init_simul(filename, test_num, cbr_num=50, div_step=1):",
"pos_mode, model, 'length') img_name_3D = get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') #",
"+ '/' + model) return folder_name + '/' def save_sk_data_to_csv(folder_name,",
"range(len(data[i])): for k in range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1)",
"cbr_num) cal_skeletons = [] for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration",
"= [] for d in data: skeletons.append(Skeleton(d)) return skeletons @check_time",
"i in range(len(data)): for j in range(len(data[i])): f.write(str(data[i][j])) if j",
"in range(len(data)): for j in range(len(data[i])): for k in range(3):",
"if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model):",
"upper_init_mean, upper_init_cov) else: print(model, \"is not exist model name\") return",
"== 2: f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name, filename, data): filename",
"skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode,",
"flt @check_time def run_ukf(ukf, skeletons, test_num): original_data = [] estimate_data",
"'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename): data = []",
"import * from calibration import Calibration from ukf_filter import ukf_Filter_Controler",
"@wraps(function) def measure(*args, **kwargs): start_time = time.time() result = function(*args,",
"= get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data = read_csv(csv_folder_name + 'original_data.csv') estimate_data",
"= folder_name + filename f = open(filename, 'w', encoding=\"UTF-8\") for",
"= folder_name + '.txt' dir_list = scan_dir(folder_name) wf = open(save_file_name,",
"os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result')",
"encoding=\"UTF-8\") for i in range(len(data)): for j in range(len(data[i])): f.write(str(data[i][j]))",
"make_folder('result') folder_name = make_folder(folder_name + '/' + person_name) folder_name =",
"open(filename, 'r') as reader: for line in reader: fields =",
"= make_folder(folder_name + '/' + model) return folder_name + '/'",
"calibration import Calibration from ukf_filter import ukf_Filter_Controler from canvas import",
"[] estimate_data = [] estimate_state = [] test_num = min(len(skeletons),",
"= [] estimate_state = [] test_num = min(len(skeletons), test_num) print(\"total",
"'original_data.csv') estimate_data = read_csv(csv_folder_name + 'estimate_data.csv') return original_data, estimate_data def",
"plot_mode) return folder_name + '/' @check_time def skeleton_draw(person_name, pos_mode, model,",
"estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data,",
"upper_init_mean, upper_init_cov, model): flt = None if model == 'ukf':",
"= init_simul(filename, test_num, cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov = set_upper_init_cov()",
"+ '/' + person_name) folder_name = make_folder(folder_name + '/' +",
"estimate_state.append(state) if i % 10 == 0: print(i, end=' ')",
"folder_name = make_folder(folder_name + '/' + model) folder_name = make_folder(folder_name",
"lower_init_mean, upper_init_mean, test_num = init_simul(filename, test_num, cbr_num) lower_init_cov = set_lower_init_cov()",
"print(i, end=' ') print('') return original_data, estimate_data, estimate_state def make_folder(folder_name):",
"= [] with open(filename, 'r') as reader: for line in",
"make_folder(folder_name + '/' + person_name) folder_name = make_folder(folder_name + '/'",
"filename = folder_name + filename f = open(filename, 'w', encoding=\"UTF-8\")",
"== (len(data[i])-1): f.write('\\n') else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data,",
"model == 'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else:",
"model) folder_name = make_folder(folder_name + '/' + plot_mode) return folder_name",
"= dir + '/' + name if os.path.isfile(path): dir_list.append(path) return",
"in range(len(data[i])): f.write(str(data[i][j])) if j == (len(data[i])-1): f.write('\\n') else: f.write(',')",
"def scan_dir(dir): dir_list = [] for name in os.listdir(dir): path",
"estimate_data.append(data) estimate_state.append(state) if i % 10 == 0: print(i, end='",
"= open(save_file_name, 'w') for filename in dir_list: f = open(filename,",
"lower_init_mean, upper_init_mean, test_num @check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model):",
"upper_init_mean, upper_init_cov, model) original_data, estimate_data, estimate_state = run_ukf(flt, skeletons, test_num)",
"= ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i % 10 == 0:",
"f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name, filename, data): filename = folder_name",
"make_folder(folder_name + '/' + model) folder_name = make_folder(folder_name + '/'",
"@check_time def simulation_ukf(filename, test_num, cbr_num, model): skeletons, lower_init_mean, upper_init_mean, test_num",
"= get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data)",
"+ '/' + name if os.path.isfile(path): dir_list.append(path) return dir_list @check_time",
"range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1) and k == 2:",
"test_num = min(test_num, len(data)) skeletons = [] for i in",
"cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt = make_filter(lower_init_mean,",
"3) skeletons = [] for d in data: skeletons.append(Skeleton(d)) return",
"def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model): flt = None if",
"skeleton_draw(person_name, pos_mode, model, original_data, estimate_data, sleep_t=100): canvas = Canvas() img_name_point",
"len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num, cbr_num,",
"is {}\".format(test_num)) print(\"test_num:\", end=' ') for i in range(test_num): curr_input",
"= function(*args, **kwargs) end_time = time.time() print(f\"@check_time: {function.__name__} took {end_time",
"i in range(len(data)): for j in range(len(data[i])): for k in",
"'/' + model) folder_name = make_folder(folder_name + '/' + plot_mode)",
"time.time() result = function(*args, **kwargs) end_time = time.time() print(f\"@check_time: {function.__name__}",
"'w', encoding=\"UTF-8\") for i in range(len(data)): for j in range(len(data[i])):",
"estimate_data, sleep_t=100): canvas = Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode, model,",
"save_sk_state_to_csv(folder_name, filename, data): filename = folder_name + filename f =",
"'estimate_state.csv', estimate_state) def read_csv(filename): data = [] with open(filename, 'r')",
"return folder_name + '/' @check_time def skeleton_draw(person_name, pos_mode, model, original_data,",
"test is {}\".format(test_num)) print(\"test_num:\", end=' ') for i in range(test_num):",
"velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4,",
"original_data.append(curr_input) state, data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i %",
"for j in range(len(data[i])): f.write(str(data[i][j])) if j == (len(data[i])-1): f.write('\\n')",
"csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data = read_csv(csv_folder_name + 'original_data.csv')",
"pos_mode, model, original_data, estimate_data, sleep_t=100): canvas = Canvas() img_name_point =",
"= make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model) original_data, estimate_data, estimate_state =",
"get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length = get_save_image_file_name(person_name, pos_mode, model, 'length')",
"measure def get_dir_name(dir): dir_list = [] for name in os.listdir(dir):",
"for i in range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state, data",
"get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t,",
"estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return",
"make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model): flt = None if model",
"else: f.write(',') def save_sk_state_to_csv(folder_name, filename, data): filename = folder_name +",
"set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model) original_data, estimate_data,",
"upper_init_cov, model): flt = None if model == 'ukf': flt",
"model, 'point') img_name_length = get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D =",
"+ '/' def save_sk_data_to_csv(folder_name, filename, data): filename = folder_name +",
"i in range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons",
"= [] for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons)",
"upper_init_cov) else: print(model, \"is not exist model name\") return flt",
"Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename) return skeletons, lower_init_mean, upper_init_mean,",
"[] test_num = min(len(skeletons), test_num) print(\"total test is {}\".format(test_num)) print(\"test_num:\",",
"open(filename, \"w\", encoding=\"UTF-8\") for i in range(len(data)): for j in",
"'/' def save_sk_data_to_csv(folder_name, filename, data): filename = folder_name + filename",
"= calibration.get_init_mean(0, filename) return skeletons, lower_init_mean, upper_init_mean, test_num @check_time def",
"original_data = [] estimate_data = [] estimate_state = [] test_num",
"2: f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name, filename, data): filename =",
"csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv',",
"filename f = open(filename, \"w\", encoding=\"UTF-8\") for i in range(len(data)):",
"in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0,",
"0: print(i, end=' ') print('') return original_data, estimate_data, estimate_state def",
"+ filename f = open(filename, 'w', encoding=\"UTF-8\") for i in",
"reader: fields = line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for i",
"dir_list = [] for name in os.listdir(dir): path = dir",
"estimate_data, estimate_state def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name",
"encoding=\"UTF-8\") for i in range(len(data)): for j in range(len(data[i])): for",
"= set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model) original_data,",
"f = open(filename, 'w', encoding=\"UTF-8\") for i in range(len(data)): for",
"upper_init_cov = set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model)",
"(len(data[i])-1): f.write('\\n') else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data,",
"(len(data[i])-1) and k == 2: f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name,",
"f.write(str(data[i][j])) if j == (len(data[i])-1): f.write('\\n') else: f.write(',') @check_time def",
"'w') for filename in dir_list: f = open(filename, 'r') line",
"os sys.path.append('./code/') from skeleton import Skeleton from read_data import *",
"dir_list: f = open(filename, 'r') line = f.readline() wf.write(line) wf.close()",
"filename = folder_name + filename f = open(filename, \"w\", encoding=\"UTF-8\")",
"k == 2: f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name, filename, data):",
"range(len(data[i])): f.write(str(data[i][j])) if j == (len(data[i])-1): f.write('\\n') else: f.write(',') @check_time",
"10 == 0: print(i, end=' ') print('') return original_data, estimate_data,",
"test_num, cbr_num, model): skeletons, lower_init_mean, upper_init_mean, test_num = init_simul(filename, test_num,",
"model) return folder_name + '/' def save_sk_data_to_csv(folder_name, filename, data): filename",
"estimate_data, estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv',",
"dir_list def scan_dir(dir): dir_list = [] for name in os.listdir(dir):",
"= skeletons[i].get_measurement() original_data.append(curr_input) state, data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if",
"= read_csv(csv_folder_name + 'estimate_data.csv') return original_data, estimate_data def get_save_image_file_name(person_name, pos_mode,",
"return original_data, estimate_data, estimate_state def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name)",
"check_time(function): @wraps(function) def measure(*args, **kwargs): start_time = time.time() result =",
"lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename) return skeletons, lower_init_mean, upper_init_mean, test_num",
"= open(filename, 'w', encoding=\"UTF-8\") for i in range(len(data)): for j",
"in dir_list: f = open(filename, 'r') line = f.readline() wf.write(line)",
"read_csv(csv_folder_name + 'original_data.csv') estimate_data = read_csv(csv_folder_name + 'estimate_data.csv') return original_data,",
"'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data,",
"test_num @check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model): flt =",
"np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons = [] for d in data:",
"start_time = time.time() result = function(*args, **kwargs) end_time = time.time()",
"'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else: print(model, \"is",
"estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def",
"i in range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state, data =",
"skeletons.append(Skeleton(d)) return skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name =",
"result return measure def get_dir_name(dir): dir_list = [] for name",
"32, 3) skeletons = [] for d in data: skeletons.append(Skeleton(d))",
"+ pos_mode) folder_name = make_folder(folder_name + '/' + model) folder_name",
"canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length)",
"model) original_data, estimate_data, estimate_state = run_ukf(flt, skeletons, test_num) return original_data,",
"model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data = read_csv(csv_folder_name +",
"get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result') folder_name = make_folder(folder_name +",
"ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i % 10 == 0: print(i,",
"get_dir_name(dir): dir_list = [] for name in os.listdir(dir): path =",
"import sys import os sys.path.append('./code/') from skeleton import Skeleton from",
"folder_name + filename f = open(filename, 'w', encoding=\"UTF-8\") for i",
"**kwargs) end_time = time.time() print(f\"@check_time: {function.__name__} took {end_time - start_time}\")",
"[] with open(filename, 'r') as reader: for line in reader:",
"in reader: fields = line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for",
"i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num) cal_skeletons =",
"if i % 10 == 0: print(i, end=' ') print('')",
"= make_folder(folder_name + '/' + person_name) folder_name = make_folder(folder_name +",
"img_name_point = get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length = get_save_image_file_name(person_name, pos_mode,",
"line = f.readline() wf.write(line) wf.close() return save_file_name @check_time def init_simul(filename,",
"'/' @check_time def skeleton_draw(person_name, pos_mode, model, original_data, estimate_data, sleep_t=100): canvas",
"make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model) original_data, estimate_data, estimate_state = run_ukf(flt,",
"dir_list = scan_dir(folder_name) wf = open(save_file_name, 'w') for filename in",
"test_num, cbr_num=50, div_step=1): data = read_data_skeleton(filename) # test_num, data =",
"data: skeletons.append(Skeleton(d)) return skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name",
"calibration.get_init_mean(0, filename) return skeletons, lower_init_mean, upper_init_mean, test_num @check_time def make_filter(lower_init_mean,",
"= dir + '/' + name if not os.path.isfile(path): dir_list.append(name)",
"os.listdir(dir): path = dir + '/' + name if not",
"= f.readline() wf.write(line) wf.close() return save_file_name @check_time def init_simul(filename, test_num,",
"set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename,",
"scan_dir(folder_name) wf = open(save_file_name, 'w') for filename in dir_list: f",
"[] for d in data: skeletons.append(Skeleton(d)) return skeletons @check_time def",
"from read_data import * from calibration import Calibration from ukf_filter",
"* import time from functools import wraps import os def",
"== 'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else: print(model,",
"make_folder(folder_name + '/' + pos_mode) folder_name = make_folder(folder_name + '/'",
"def merge_skeleton_data(folder_name): save_file_name = folder_name + '.txt' dir_list = scan_dir(folder_name)",
"model, plot_mode): folder_name = make_folder('result') folder_name = make_folder(folder_name + '/'",
"ukf_Filter_Controler from canvas import Canvas from regression import * import",
"original_data, estimate_data def get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name = make_folder('result')",
"end_time = time.time() print(f\"@check_time: {function.__name__} took {end_time - start_time}\") return",
"return skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name,",
"= read_csv(csv_folder_name + 'original_data.csv') estimate_data = read_csv(csv_folder_name + 'estimate_data.csv') return",
"'point') img_name_length = get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D = get_save_image_file_name(person_name,",
"folder_name = make_folder(folder_name + '/' + model) return folder_name +",
"i % 10 == 0: print(i, end=' ') print('') return",
"filename in dir_list: f = open(filename, 'r') line = f.readline()",
"skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num) cal_skeletons = [] for i",
"j == (len(data[i])-1): f.write('\\n') else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode,",
"pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D)",
"f.readline() wf.write(line) wf.close() return save_file_name @check_time def init_simul(filename, test_num, cbr_num=50,",
"<gh_stars>1-10 import sys import os sys.path.append('./code/') from skeleton import Skeleton",
"person_name) folder_name = make_folder(folder_name + '/' + pos_mode) folder_name =",
"velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num,",
"@check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state, model): csv_folder_name =",
"= min(len(skeletons), test_num) print(\"total test is {}\".format(test_num)) print(\"test_num:\", end=' ')",
"fields[len(fields)-1].replace('\\n', '') for i in range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3),",
"* from calibration import Calibration from ukf_filter import ukf_Filter_Controler from",
"original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename): data",
"cbr_num = min(test_num, cbr_num) cal_skeletons = [] for i in",
"functools import wraps import os def check_time(function): @wraps(function) def measure(*args,",
"init_simul(filename, test_num, cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt",
"get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data = read_csv(csv_folder_name + 'original_data.csv') estimate_data =",
"range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons = []",
"result = function(*args, **kwargs) end_time = time.time() print(f\"@check_time: {function.__name__} took",
"in range(len(data[i])): for k in range(3): f.write(str(data[i][j][k])) if j ==",
"# canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point)",
"f.write(',') @check_time def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state, model): csv_folder_name",
"[] for i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num)",
"estimate_data, estimate_state = run_ukf(flt, skeletons, test_num) return original_data, estimate_data, estimate_state",
"velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov,",
"filename, data): filename = folder_name + filename f = open(filename,",
"test_num = init_simul(filename, test_num, cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov =",
"if not os.path.isfile(path): dir_list.append(name) return dir_list def scan_dir(dir): dir_list =",
"% 10 == 0: print(i, end=' ') print('') return original_data,",
"from ukf_filter import ukf_Filter_Controler from canvas import Canvas from regression",
"d in data: skeletons.append(Skeleton(d)) return skeletons @check_time def read_skeleton_data_from_csv(person_name, pos_mode,",
"range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename)",
"pos_mode, model): folder_name = make_folder('result') folder_name = make_folder(folder_name + '/'",
"original_data, estimate_data, estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name,",
"save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename): data =",
"upper_init_mean, test_num = init_simul(filename, test_num, cbr_num) lower_init_cov = set_lower_init_cov() upper_init_cov",
"skeletons, lower_init_mean, upper_init_mean, test_num @check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov,",
"set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov,",
"data = [] with open(filename, 'r') as reader: for line",
"= open(filename, \"w\", encoding=\"UTF-8\") for i in range(len(data)): for j",
"return original_data, estimate_data def get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name =",
"skeletons[i].get_measurement() original_data.append(curr_input) state, data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i",
"merge_skeleton_data(folder_name): save_file_name = folder_name + '.txt' dir_list = scan_dir(folder_name) wf",
"in range(len(data)): for j in range(len(data[i])): f.write(str(data[i][j])) if j ==",
"from canvas import Canvas from regression import * import time",
"reader: for line in reader: fields = line.split(',') fields[len(fields)-1] =",
"trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num, cbr_num, model): skeletons,",
"estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10,",
"return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result') folder_name",
"min(test_num, cbr_num) cal_skeletons = [] for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step])",
"set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov,",
"[value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num, cbr_num, model): skeletons, lower_init_mean, upper_init_mean,",
"def save_sk_state_to_csv(folder_name, filename, data): filename = folder_name + filename f",
"save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename): data = [] with open(filename,",
"took {end_time - start_time}\") return result return measure def get_dir_name(dir):",
"folder_name + '.txt' dir_list = scan_dir(folder_name) wf = open(save_file_name, 'w')",
"pos_mode, model) original_data = read_csv(csv_folder_name + 'original_data.csv') estimate_data = read_csv(csv_folder_name",
"pos_mode, original_data, estimate_data, estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model)",
"pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv',",
"return dir_list def scan_dir(dir): dir_list = [] for name in",
"model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data,",
"velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return",
"estimate_data = read_csv(csv_folder_name + 'estimate_data.csv') return original_data, estimate_data def get_save_image_file_name(person_name,",
"pos_mode) folder_name = make_folder(folder_name + '/' + model) folder_name =",
"model): skeletons, lower_init_mean, upper_init_mean, test_num = init_simul(filename, test_num, cbr_num) lower_init_cov",
"in os.listdir(dir): path = dir + '/' + name if",
"= make_folder('result') folder_name = make_folder(folder_name + '/' + person_name) folder_name",
"for d in data: skeletons.append(Skeleton(d)) return skeletons @check_time def read_skeleton_data_from_csv(person_name,",
"exist model name\") return flt @check_time def run_ukf(ukf, skeletons, test_num):",
"canvas import Canvas from regression import * import time from",
"folder_name = make_folder('result') folder_name = make_folder(folder_name + '/' + person_name)",
"model): folder_name = make_folder('result') folder_name = make_folder(folder_name + '/' +",
"get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name = make_folder('result') folder_name = make_folder(folder_name",
"fields = line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for i in",
"+ name if not os.path.isfile(path): dir_list.append(name) return dir_list def scan_dir(dir):",
"for name in os.listdir(dir): path = dir + '/' +",
"div_step) test_num = min(test_num, len(data)) skeletons = [] for i",
"velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4,",
"else: print(model, \"is not exist model name\") return flt @check_time",
"def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result') folder_name = make_folder(folder_name",
"state, data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i % 10",
"cbr_num=50, div_step=1): data = read_data_skeleton(filename) # test_num, data = interval_compasation(data,",
"for i in range(len(data)): for j in range(len(data[i])): f.write(str(data[i][j])) if",
"j in range(len(data[i])): f.write(str(data[i][j])) if j == (len(data[i])-1): f.write('\\n') else:",
"folder_name + '/' def save_sk_data_to_csv(folder_name, filename, data): filename = folder_name",
"line in reader: fields = line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '')",
"return measure def get_dir_name(dir): dir_list = [] for name in",
"@check_time def init_simul(filename, test_num, cbr_num=50, div_step=1): data = read_data_skeleton(filename) #",
"for i in range(len(data)): for j in range(len(data[i])): for k",
"{}\".format(test_num)) print(\"test_num:\", end=' ') for i in range(test_num): curr_input =",
"open(filename, 'w', encoding=\"UTF-8\") for i in range(len(data)): for j in",
"print(f\"@check_time: {function.__name__} took {end_time - start_time}\") return result return measure",
"= set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean,",
"flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else: print(model, \"is not",
"if j == (len(data[i])-1): f.write('\\n') else: f.write(',') @check_time def save_skeleton_data_to_csv(person_name,",
"wraps import os def check_time(function): @wraps(function) def measure(*args, **kwargs): start_time",
"with open(filename, 'r') as reader: for line in reader: fields",
"velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov,",
"def get_dir_name(dir): dir_list = [] for name in os.listdir(dir): path",
"= None if model == 'ukf': flt = ukf_Filter_Controler(lower_init_mean, lower_init_cov,",
"make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode,",
"as reader: for line in reader: fields = line.split(',') fields[len(fields)-1]",
"= [] for i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num,",
"f.write(',') def save_sk_state_to_csv(folder_name, filename, data): filename = folder_name + filename",
"path = dir + '/' + name if os.path.isfile(path): dir_list.append(path)",
"= [] for name in os.listdir(dir): path = dir +",
"lower_init_cov, upper_init_mean, upper_init_cov, model) original_data, estimate_data, estimate_state = run_ukf(flt, skeletons,",
"canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data, sleep_t, img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data,",
"for i in range(cbr_num): cal_skeletons.append(skeletons[i*div_step]) calibration = Calibration(cal_skeletons) lower_init_mean, upper_init_mean",
"range(len(data)): for j in range(len(data[i])): for k in range(3): f.write(str(data[i][j][k]))",
"skeletons = [] for i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num =",
"'estimate_data.csv') return original_data, estimate_data def get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name",
"original_data, estimate_data, estimate_state def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return",
"pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data = read_csv(csv_folder_name",
"measure(*args, **kwargs): start_time = time.time() result = function(*args, **kwargs) end_time",
"regression import * import time from functools import wraps import",
"def save_skeleton_data_to_csv(person_name, pos_mode, original_data, estimate_data, estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name,",
"path = dir + '/' + name if not os.path.isfile(path):",
"def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data",
"trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time",
"end=' ') print('') return original_data, estimate_data, estimate_state def make_folder(folder_name): if",
"'r') as reader: for line in reader: fields = line.split(',')",
"sleep_t=100): canvas = Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode, model, 'point')",
"test_num) print(\"total test is {}\".format(test_num)) print(\"test_num:\", end=' ') for i",
"def save_sk_data_to_csv(folder_name, filename, data): filename = folder_name + filename f",
"upper_init_mean, test_num @check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model): flt",
"time.time() print(f\"@check_time: {function.__name__} took {end_time - start_time}\") return result return",
"data = ukf.update(curr_input) estimate_data.append(data) estimate_state.append(state) if i % 10 ==",
"for filename in dir_list: f = open(filename, 'r') line =",
"= ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else: print(model, \"is not exist",
"= line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n', '') for i in range(len(fields)):",
"original_data, estimate_data, sleep_t=100): canvas = Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode,",
"wf = open(save_file_name, 'w') for filename in dir_list: f =",
"for i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num = min(test_num, cbr_num) cal_skeletons",
"sys.path.append('./code/') from skeleton import Skeleton from read_data import * from",
"+ 'original_data.csv') estimate_data = read_csv(csv_folder_name + 'estimate_data.csv') return original_data, estimate_data",
"') for i in range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state,",
"run_ukf(ukf, skeletons, test_num): original_data = [] estimate_data = [] estimate_state",
"div_step=1): data = read_data_skeleton(filename) # test_num, data = interval_compasation(data, test_num,",
"min(len(skeletons), test_num) print(\"total test is {}\".format(test_num)) print(\"test_num:\", end=' ') for",
"= min(test_num, len(data)) skeletons = [] for i in range(test_num):",
"[] estimate_state = [] test_num = min(len(skeletons), test_num) print(\"total test",
"[] for name in os.listdir(dir): path = dir + '/'",
"= Calibration(cal_skeletons) lower_init_mean, upper_init_mean = calibration.get_init_mean(0, filename) return skeletons, lower_init_mean,",
"flt = make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model) original_data, estimate_data, estimate_state",
"estimate_state def make_folder(folder_name): if not os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def",
"+ person_name) folder_name = make_folder(folder_name + '/' + pos_mode) folder_name",
"+ '/' + model) folder_name = make_folder(folder_name + '/' +",
"folder_name + filename f = open(filename, \"w\", encoding=\"UTF-8\") for i",
"\"w\", encoding=\"UTF-8\") for i in range(len(data)): for j in range(len(data[i])):",
"if os.path.isfile(path): dir_list.append(path) return dir_list @check_time def merge_skeleton_data(folder_name): save_file_name =",
"sys import os sys.path.append('./code/') from skeleton import Skeleton from read_data",
"= time.time() print(f\"@check_time: {function.__name__} took {end_time - start_time}\") return result",
"test_num, div_step) test_num = min(test_num, len(data)) skeletons = [] for",
"upper_init_mean = calibration.get_init_mean(0, filename) return skeletons, lower_init_mean, upper_init_mean, test_num @check_time",
"print('') return original_data, estimate_data, estimate_state def make_folder(folder_name): if not os.path.isdir(folder_name):",
"folder_name + '/' @check_time def skeleton_draw(person_name, pos_mode, model, original_data, estimate_data,",
"from skeleton import Skeleton from read_data import * from calibration",
"+ pos_mode) folder_name = make_folder(folder_name + '/' + model) return",
"= get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data, estimate_data,",
"Canvas from regression import * import time from functools import",
"model name\") return flt @check_time def run_ukf(ukf, skeletons, test_num): original_data",
"def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def",
"min(test_num, len(data)) skeletons = [] for i in range(test_num): skeletons.append(Skeleton(data[i]))",
"skeletons = [] for d in data: skeletons.append(Skeleton(d)) return skeletons",
"folder_name = make_folder(folder_name + '/' + plot_mode) return folder_name +",
"filename) return skeletons, lower_init_mean, upper_init_mean, test_num @check_time def make_filter(lower_init_mean, lower_init_cov,",
"skeleton import Skeleton from read_data import * from calibration import",
"import Canvas from regression import * import time from functools",
"= np.array(data).reshape((int)(len(data)/32/3), 32, 3) skeletons = [] for d in",
"= open(filename, 'r') line = f.readline() wf.write(line) wf.close() return save_file_name",
"@check_time def read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model)",
"in range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state, data = ukf.update(curr_input)",
"range(len(data)): for j in range(len(data[i])): f.write(str(data[i][j])) if j == (len(data[i])-1):",
"def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov, velo_cov_0,value_cov,",
"import Calibration from ukf_filter import ukf_Filter_Controler from canvas import Canvas",
"f = open(filename, 'r') line = f.readline() wf.write(line) wf.close() return",
"test_num = min(len(skeletons), test_num) print(\"total test is {}\".format(test_num)) print(\"test_num:\", end='",
"get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name,",
"data = interval_compasation(data, test_num, div_step) test_num = min(test_num, len(data)) skeletons",
"estimate_state) def read_csv(filename): data = [] with open(filename, 'r') as",
"len(data)) skeletons = [] for i in range(test_num): skeletons.append(Skeleton(data[i])) cbr_num",
"'') for i in range(len(fields)): data.append(float(fields[i])) data = np.array(data).reshape((int)(len(data)/32/3), 32,",
"'/' + name if os.path.isfile(path): dir_list.append(path) return dir_list @check_time def",
"for line in reader: fields = line.split(',') fields[len(fields)-1] = fields[len(fields)-1].replace('\\n',",
"def get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name = make_folder('result') folder_name =",
"import os def check_time(function): @wraps(function) def measure(*args, **kwargs): start_time =",
"data): filename = folder_name + filename f = open(filename, 'w',",
"from functools import wraps import os def check_time(function): @wraps(function) def",
"@check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov, model): flt = None",
"img_name_3D) canvas.skeleton_point_plot(original_data, estimate_data, img_name_point) canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4,",
"not os.path.isfile(path): dir_list.append(name) return dir_list def scan_dir(dir): dir_list = []",
"+ filename f = open(filename, \"w\", encoding=\"UTF-8\") for i in",
"for k in range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1) and",
"def init_simul(filename, test_num, cbr_num=50, div_step=1): data = read_data_skeleton(filename) # test_num,",
"return folder_name + '/' def save_sk_data_to_csv(folder_name, filename, data): filename =",
"k in range(3): f.write(str(data[i][j][k])) if j == (len(data[i])-1) and k",
"cbr_num, model): skeletons, lower_init_mean, upper_init_mean, test_num = init_simul(filename, test_num, cbr_num)",
"+ '/' + plot_mode) return folder_name + '/' @check_time def",
"= scan_dir(folder_name) wf = open(save_file_name, 'w') for filename in dir_list:",
"and k == 2: f.write('\\n') else: f.write(',') def save_sk_state_to_csv(folder_name, filename,",
"canvas = Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length",
"skeletons, lower_init_mean, upper_init_mean, test_num = init_simul(filename, test_num, cbr_num) lower_init_cov =",
"return skeletons, lower_init_mean, upper_init_mean, test_num @check_time def make_filter(lower_init_mean, lower_init_cov, upper_init_mean,",
"img_name_length = get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D = get_save_image_file_name(person_name, pos_mode,",
"img_name_3D = get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data) canvas.skeleton_3D_animation_save(original_data,",
"from calibration import Calibration from ukf_filter import ukf_Filter_Controler from canvas",
"os.path.isdir(folder_name): os.mkdir(folder_name) return folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name =",
"read_csv(csv_folder_name + 'estimate_data.csv') return original_data, estimate_data def get_save_image_file_name(person_name, pos_mode, model,",
"test_num, data = interval_compasation(data, test_num, div_step) test_num = min(test_num, len(data))",
"model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name,",
"return dir_list @check_time def merge_skeleton_data(folder_name): save_file_name = folder_name + '.txt'",
"wf.close() return save_file_name @check_time def init_simul(filename, test_num, cbr_num=50, div_step=1): data",
"import time from functools import wraps import os def check_time(function):",
"def read_csv(filename): data = [] with open(filename, 'r') as reader:",
"estimate_data def get_save_image_file_name(person_name, pos_mode, model, plot_mode): folder_name = make_folder('result') folder_name",
"+ '.txt' dir_list = scan_dir(folder_name) wf = open(save_file_name, 'w') for",
"= Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length =",
"original_data = read_csv(csv_folder_name + 'original_data.csv') estimate_data = read_csv(csv_folder_name + 'estimate_data.csv')",
"interval_compasation(data, test_num, div_step) test_num = min(test_num, len(data)) skeletons = []",
"'/' + person_name) folder_name = make_folder(folder_name + '/' + pos_mode)",
"return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num, cbr_num, model): skeletons, lower_init_mean,",
"start_time}\") return result return measure def get_dir_name(dir): dir_list = []",
"os.path.isfile(path): dir_list.append(name) return dir_list def scan_dir(dir): dir_list = [] for",
"obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor] @check_time def simulation_ukf(filename, test_num, cbr_num, model):",
"canvas.skeleton_length_plot(original_data, estimate_data, img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100):",
"Skeleton from read_data import * from calibration import Calibration from",
"make_folder(folder_name + '/' + model) return folder_name + '/' def",
"import os sys.path.append('./code/') from skeleton import Skeleton from read_data import",
"+ name if os.path.isfile(path): dir_list.append(path) return dir_list @check_time def merge_skeleton_data(folder_name):",
"'.txt' dir_list = scan_dir(folder_name) wf = open(save_file_name, 'w') for filename",
"= folder_name + filename f = open(filename, \"w\", encoding=\"UTF-8\") for",
"original_data, estimate_data, estimate_state = run_ukf(flt, skeletons, test_num) return original_data, estimate_data,",
"'original_data.csv', original_data) save_sk_data_to_csv(csv_folder_name, 'estimate_data.csv', estimate_data) save_sk_state_to_csv(csv_folder_name, 'estimate_state.csv', estimate_state) def read_csv(filename):",
"+ '/' @check_time def skeleton_draw(person_name, pos_mode, model, original_data, estimate_data, sleep_t=100):",
"Canvas() img_name_point = get_save_image_file_name(person_name, pos_mode, model, 'point') img_name_length = get_save_image_file_name(person_name,",
"get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D = get_save_image_file_name(person_name, pos_mode, model, 'plot_3D')",
"lower_init_cov = set_lower_init_cov() upper_init_cov = set_upper_init_cov() flt = make_filter(lower_init_mean, lower_init_cov,",
"ukf_filter import ukf_Filter_Controler from canvas import Canvas from regression import",
"print(\"total test is {}\".format(test_num)) print(\"test_num:\", end=' ') for i in",
"estimate_state, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) save_sk_data_to_csv(csv_folder_name, 'original_data.csv', original_data)",
"ukf_Filter_Controler(lower_init_mean, lower_init_cov, upper_init_mean, upper_init_cov) else: print(model, \"is not exist model",
"+ model) folder_name = make_folder(folder_name + '/' + plot_mode) return",
"dir + '/' + name if os.path.isfile(path): dir_list.append(path) return dir_list",
"== (len(data[i])-1) and k == 2: f.write('\\n') else: f.write(',') def",
"return [value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def",
"j in range(len(data[i])): for k in range(3): f.write(str(data[i][j][k])) if j",
"def run_ukf(ukf, skeletons, test_num): original_data = [] estimate_data = []",
"img_name_length) def set_lower_init_cov(value_cov=1e-6, velo_cov_0=1e-4, velo_cov_1=1e-2, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,",
"'length') img_name_3D = get_save_image_file_name(person_name, pos_mode, model, 'plot_3D') # canvas.skeleton_3D_plot(original_data, estimate_data)",
"lower_init_cov, upper_init_mean, upper_init_cov, model): flt = None if model ==",
"range(test_num): curr_input = skeletons[i].get_measurement() original_data.append(curr_input) state, data = ukf.update(curr_input) estimate_data.append(data)",
"[value_cov, velo_cov_0,value_cov, velo_cov_0,value_cov, velo_cov_1,value_cov, velo_cov_1,value_cov, velo_cov_0, len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6,",
"') print('') return original_data, estimate_data, estimate_state def make_folder(folder_name): if not",
"os.path.isfile(path): dir_list.append(path) return dir_list @check_time def merge_skeleton_data(folder_name): save_file_name = folder_name",
"filename f = open(filename, 'w', encoding=\"UTF-8\") for i in range(len(data)):",
"model) original_data = read_csv(csv_folder_name + 'original_data.csv') estimate_data = read_csv(csv_folder_name +",
"'/' + model) return folder_name + '/' def save_sk_data_to_csv(folder_name, filename,",
"f = open(filename, \"w\", encoding=\"UTF-8\") for i in range(len(data)): for",
"len_cov,obs_cov_factor, trans_factor] def set_upper_init_cov(value_cov=1e-6, velo_cov=1e-4, len_cov=1e-10, obs_cov_factor=1e-4, trans_factor=100): return [value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,value_cov,velo_cov,len_cov,obs_cov_factor,trans_factor]",
"'r') line = f.readline() wf.write(line) wf.close() return save_file_name @check_time def",
"= time.time() result = function(*args, **kwargs) end_time = time.time() print(f\"@check_time:",
"read_data_skeleton(filename) # test_num, data = interval_compasation(data, test_num, div_step) test_num =",
"folder_name def get_save_skeleton_data_folder_name(person_name, pos_mode, model): folder_name = make_folder('result') folder_name =",
"estimate_data = [] estimate_state = [] test_num = min(len(skeletons), test_num)",
"{function.__name__} took {end_time - start_time}\") return result return measure def",
"read_skeleton_data_from_csv(person_name, pos_mode, model): csv_folder_name = get_save_skeleton_data_folder_name(person_name, pos_mode, model) original_data =",
"+ plot_mode) return folder_name + '/' @check_time def skeleton_draw(person_name, pos_mode,",
"= get_save_image_file_name(person_name, pos_mode, model, 'length') img_name_3D = get_save_image_file_name(person_name, pos_mode, model,",
"init_simul(filename, test_num, cbr_num=50, div_step=1): data = read_data_skeleton(filename) # test_num, data"
] |
[
"if not admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True)",
"import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User",
") revision.publish() # Archived Events Browse Filterable Page if not",
"root if not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port = 8000",
"else: site_root = site_root[0] # Setting new site root if",
"from django.contrib.auth.models import User from wagtail.wagtailcore.models import Page, Site from",
"run(): print('Running script \\'scripts.initial_data\\' ...') admin_user = None site_root =",
"new site root if not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port",
"revision = events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish() # Archived Events",
"events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision( user=admin_user,",
"events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision = archived_events.save_revision( user=admin_user, submitted_for_moderation=False, )",
"Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() # Events Browse Page required for",
"admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save() else: admin_user",
"slug='home-page', depth=2, owner=admin_user) site_root.live = True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user,",
"# Setting new site root if not Site.objects.filter(hostname='content.localhost').exists(): site =",
"= events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish() # Archived Events Browse",
"root `CFGov` site_root = HomePage.objects.filter(title='CFGOV') if not site_root: root =",
"root = Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live",
"Page required for event `import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events",
"import make_password from django.contrib.auth.models import User from wagtail.wagtailcore.models import Page,",
"User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save() else: admin_user = admin_user[0]",
"site_root.add_child(instance=events) revision = events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish() # Archived",
"= BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision( user=admin_user, submitted_for_moderation=False,",
"Archived Events Browse Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events =",
"root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root = site_root[0]",
"site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root = site_root[0] # Setting new",
"print_function import json import os from django.conf import settings from",
"site_root = None events = None admin_user = User.objects.filter(username='admin') if",
"a new site root `CFGov` site_root = HomePage.objects.filter(title='CFGOV') if not",
"v1.models import HomePage, BrowseFilterablePage def run(): print('Running script \\'scripts.initial_data\\' ...')",
"= User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save() else: admin_user =",
"Creates a new site root `CFGov` site_root = HomePage.objects.filter(title='CFGOV') if",
"if old_site_root: old_site_root.delete() # Events Browse Page required for event",
"BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events)",
"site_root = site_root[0] # Setting new site root if not",
"submitted_for_moderation=False) latest.save() else: site_root = site_root[0] # Setting new site",
"not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not events:",
"Up old_site_root = Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() # Events Browse",
"BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not events: events",
"Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if",
"True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root =",
"old_site_root = Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() # Events Browse Page",
"django.contrib.auth.models import User from wagtail.wagtailcore.models import Page, Site from v1.models",
"Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() # Clean Up old_site_root = Page.objects.filter(id=2)[0]",
"= BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision = archived_events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish()",
"User.objects.filter(username='admin') if not admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True,",
"= site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root = site_root[0] # Setting",
"for event `import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events',",
"slug='events', owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish()",
"...') admin_user = None site_root = None events = None",
"admin_user[0] # Creates a new site root `CFGov` site_root =",
"site_root.id site.save() content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() # Clean",
"if not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision",
"root_page_id=site_root.id) content_site.save() # Clean Up old_site_root = Page.objects.filter(id=2)[0] if old_site_root:",
"# Archived Events Browse Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events",
"= admin_user[0] # Creates a new site root `CFGov` site_root",
"= Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() # Events Browse Page required",
"latest.save() else: site_root = site_root[0] # Setting new site root",
"events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish() # Archived Events Browse Filterable",
"= Site.objects.first() site.port = 8000 site.root_page_id = site_root.id site.save() content_site",
"archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not events: events =",
"is_superuser=True, is_active=True, is_staff=True) admin_user.save() else: admin_user = admin_user[0] # Creates",
"Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live = True",
"= BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not events: events = BrowseFilterablePage.objects.get(title='Events')",
"admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save() else:",
"from django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models",
"import HomePage, BrowseFilterablePage def run(): print('Running script \\'scripts.initial_data\\' ...') admin_user",
"Browse Page required for event `import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists():",
"submitted_for_moderation=False, ) revision.publish() # Archived Events Browse Filterable Page if",
"from wagtail.wagtailcore.models import Page, Site from v1.models import HomePage, BrowseFilterablePage",
"old_site_root: old_site_root.delete() # Events Browse Page required for event `import-data`",
"Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user)",
"admin_user.save() else: admin_user = admin_user[0] # Creates a new site",
"= HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live = True root.add_child(instance=site_root) latest",
"__future__ import print_function import json import os from django.conf import",
"depth=2, owner=admin_user) site_root.live = True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False)",
"make_password from django.contrib.auth.models import User from wagtail.wagtailcore.models import Page, Site",
"django.conf import settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import",
"script \\'scripts.initial_data\\' ...') admin_user = None site_root = None events",
"old_site_root.delete() # Events Browse Page required for event `import-data` command",
"= None site_root = None events = None admin_user =",
"Clean Up old_site_root = Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() # Events",
"= 8000 site.root_page_id = site_root.id site.save() content_site = Site(hostname='content.localhost', port=8000,",
"site.port = 8000 site.root_page_id = site_root.id site.save() content_site = Site(hostname='content.localhost',",
"if not events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision = archived_events.save_revision(",
"Site from v1.models import HomePage, BrowseFilterablePage def run(): print('Running script",
"= None admin_user = User.objects.filter(username='admin') if not admin_user: admin_user =",
"def run(): print('Running script \\'scripts.initial_data\\' ...') admin_user = None site_root",
"HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live = True root.add_child(instance=site_root) latest =",
"import Page, Site from v1.models import HomePage, BrowseFilterablePage def run():",
"= None events = None admin_user = User.objects.filter(username='admin') if not",
"import User from wagtail.wagtailcore.models import Page, Site from v1.models import",
"json import os from django.conf import settings from django.contrib.auth.hashers import",
"is_staff=True) admin_user.save() else: admin_user = admin_user[0] # Creates a new",
"Setting new site root if not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first()",
"# Clean Up old_site_root = Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete() #",
"HomePage, BrowseFilterablePage def run(): print('Running script \\'scripts.initial_data\\' ...') admin_user =",
"Site.objects.first() site.port = 8000 site.root_page_id = site_root.id site.save() content_site =",
"= site_root[0] # Setting new site root if not Site.objects.filter(hostname='content.localhost').exists():",
"admin_user = None site_root = None events = None admin_user",
"= HomePage.objects.filter(title='CFGOV') if not site_root: root = Page.objects.first() site_root =",
"= Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() # Clean Up old_site_root =",
"port=8000, root_page_id=site_root.id) content_site.save() # Clean Up old_site_root = Page.objects.filter(id=2)[0] if",
"site.root_page_id = site_root.id site.save() content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save()",
"Events Browse Page required for event `import-data` command if not",
"site root `CFGov` site_root = HomePage.objects.filter(title='CFGOV') if not site_root: root",
"Page, Site from v1.models import HomePage, BrowseFilterablePage def run(): print('Running",
"owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision( user=admin_user, submitted_for_moderation=False, ) revision.publish() #",
"is_active=True, is_staff=True) admin_user.save() else: admin_user = admin_user[0] # Creates a",
"site = Site.objects.first() site.port = 8000 site.root_page_id = site_root.id site.save()",
"None admin_user = User.objects.filter(username='admin') if not admin_user: admin_user = User(username='admin',",
"admin_user = User.objects.filter(username='admin') if not admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')),",
"= True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root",
"site root if not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port =",
"Events Browse Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive',",
"owner=admin_user) if not events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision =",
"BrowseFilterablePage def run(): print('Running script \\'scripts.initial_data\\' ...') admin_user = None",
"slug='archive', owner=admin_user) if not events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision",
"= Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live =",
"`CFGov` site_root = HomePage.objects.filter(title='CFGOV') if not site_root: root = Page.objects.first()",
"from __future__ import print_function import json import os from django.conf",
"django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from wagtail.wagtailcore.models import",
"site_root: root = Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user)",
"site_root.live = True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else:",
"latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save() else: site_root = site_root[0] #",
"content_site.save() # Clean Up old_site_root = Page.objects.filter(id=2)[0] if old_site_root: old_site_root.delete()",
"import os from django.conf import settings from django.contrib.auth.hashers import make_password",
"new site root `CFGov` site_root = HomePage.objects.filter(title='CFGOV') if not site_root:",
"Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port = 8000 site.root_page_id = site_root.id",
"site.save() content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() # Clean Up",
"revision.publish() # Archived Events Browse Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists():",
"owner=admin_user) site_root.live = True root.add_child(instance=site_root) latest = site_root.save_revision(user=admin_user, submitted_for_moderation=False) latest.save()",
"import print_function import json import os from django.conf import settings",
"None site_root = None events = None admin_user = User.objects.filter(username='admin')",
"not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port = 8000 site.root_page_id =",
"\\'scripts.initial_data\\' ...') admin_user = None site_root = None events =",
"site_root[0] # Setting new site root if not Site.objects.filter(hostname='content.localhost').exists(): site",
"BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision( user=admin_user, submitted_for_moderation=False, )",
"os from django.conf import settings from django.contrib.auth.hashers import make_password from",
"admin_user = admin_user[0] # Creates a new site root `CFGov`",
"`import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user)",
"events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision = archived_events.save_revision( user=admin_user, submitted_for_moderation=False,",
"command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events)",
"from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from wagtail.wagtailcore.models",
"wagtail.wagtailcore.models import Page, Site from v1.models import HomePage, BrowseFilterablePage def",
"if not site_root: root = Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page',",
"settings from django.contrib.auth.hashers import make_password from django.contrib.auth.models import User from",
"print('Running script \\'scripts.initial_data\\' ...') admin_user = None site_root = None",
"None events = None admin_user = User.objects.filter(username='admin') if not admin_user:",
"password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save() else: admin_user = admin_user[0] #",
"not admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True, is_active=True, is_staff=True) admin_user.save()",
"not site_root: root = Page.objects.first() site_root = HomePage(title='CFGOV', slug='home-page', depth=2,",
"# Creates a new site root `CFGov` site_root = HomePage.objects.filter(title='CFGOV')",
"HomePage.objects.filter(title='CFGOV') if not site_root: root = Page.objects.first() site_root = HomePage(title='CFGOV',",
"not events: events = BrowseFilterablePage.objects.get(title='Events') events.add_child(instance=archived_events) revision = archived_events.save_revision( user=admin_user,",
"# Events Browse Page required for event `import-data` command if",
"= site_root.id site.save() content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() #",
"Browse Filterable Page if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive',",
"else: admin_user = admin_user[0] # Creates a new site root",
"site_root = HomePage(title='CFGOV', slug='home-page', depth=2, owner=admin_user) site_root.live = True root.add_child(instance=site_root)",
"BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision = events.save_revision(",
"User from wagtail.wagtailcore.models import Page, Site from v1.models import HomePage,",
"not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events', owner=admin_user) site_root.add_child(instance=events) revision =",
"if not Site.objects.filter(hostname='content.localhost').exists(): site = Site.objects.first() site.port = 8000 site.root_page_id",
"required for event `import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events =",
"from v1.models import HomePage, BrowseFilterablePage def run(): print('Running script \\'scripts.initial_data\\'",
"site_root = HomePage.objects.filter(title='CFGOV') if not site_root: root = Page.objects.first() site_root",
"content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id) content_site.save() # Clean Up old_site_root",
"8000 site.root_page_id = site_root.id site.save() content_site = Site(hostname='content.localhost', port=8000, root_page_id=site_root.id)",
"event `import-data` command if not BrowseFilterablePage.objects.filter(title='Events').exists(): events = BrowseFilterablePage(title='Events', slug='events',",
"import json import os from django.conf import settings from django.contrib.auth.hashers",
"if not BrowseFilterablePage.objects.filter(title='Archive').exists(): archived_events = BrowseFilterablePage(title='Archive', slug='archive', owner=admin_user) if not",
"user=admin_user, submitted_for_moderation=False, ) revision.publish() # Archived Events Browse Filterable Page",
"events = None admin_user = User.objects.filter(username='admin') if not admin_user: admin_user",
"= User.objects.filter(username='admin') if not admin_user: admin_user = User(username='admin', password=make_password(os.environ.get('WAGTAIL_ADMIN_PW')), is_superuser=True,"
] |
[
"print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value ==",
"end = \" \") print(\"\\nGot:\", end=\"\") for j in range(0,",
"print(maximal_error.shape) for i in range(0, 5): print(\"Image\", i) print(\"Expected:\", end=\"\")",
"10): print(out_ref[i, j], end = \" \") print(\"\\nGot:\", end=\"\") for",
"does not match the reference.\") maximal_error = np.amax(error, axis=1) print(maximal_error.shape)",
"files do not contain the same number of outputs.\") print(\"The",
"end=\"\") for j in range(0, 10): print(out_ref[i, j], end =",
"out_ref.shape: print(\"The files do not contain the same number of",
"the reference is {0}.\".format(maximal_error)) if maximal_error < 10**(-6): print(\"OK:Output seems",
"< 10**(-6): print(\"OK:Output seems to match the reference.\") sys.exit(0) print(\"Failure:Output",
"0.0] = 1.0 error = (out_ref - out) / ref_value",
"error between the output and the reference is {0}.\".format(maximal_error)) if",
"the reference.\") maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for i in",
"# Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import h5py",
"numpy as np if len(sys.argv) != 3: print(\"Expected two arguments.",
"10**(-6): print(\"OK:Output seems to match the reference.\") sys.exit(0) print(\"Failure:Output does",
"5): print(\"Image\", i) print(\"Expected:\", end=\"\") for j in range(0, 10):",
"= h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r') out = np.array(f['output_data'])",
"size: {0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref)",
"match the reference.\") sys.exit(0) print(\"Failure:Output does not match the reference.\")",
"sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0 error",
"print(\"Failure:Output does not match the reference.\") maximal_error = np.amax(error, axis=1)",
"{0}.\".format(maximal_error)) if maximal_error < 10**(-6): print(\"OK:Output seems to match the",
"<filename>Scripts/compareOutputs.py<gh_stars>0 # Simple python3 script to compare output with a",
"same number of outputs.\") print(\"The output size: {0}.\".format(out.shape[0])) print(\"The reference",
"testOutput.h5 testRefOutput.h5 import sys import h5py import numpy as np",
"compare output with a reference output. # Usage: python3 compareOutputs.py",
"i in range(0, 5): print(\"Image\", i) print(\"Expected:\", end=\"\") for j",
"print(\"The output size: {0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value",
"print(\"The files do not contain the same number of outputs.\")",
"reference output file.\") sys.exit(1) filename = sys.argv[1] ref_filename = sys.argv[2]",
"contain the same number of outputs.\") print(\"The output size: {0}.\".format(out.shape[0]))",
"(out_ref - out) / ref_value maximal_error = np.amax(error) print(\"Maximal error",
"Output and reference output file.\") sys.exit(1) filename = sys.argv[1] ref_filename",
"reference is {0}.\".format(maximal_error)) if maximal_error < 10**(-6): print(\"OK:Output seems to",
"output and the reference is {0}.\".format(maximal_error)) if maximal_error < 10**(-6):",
"for i in range(0, 5): print(\"Image\", i) print(\"Expected:\", end=\"\") for",
"= np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape != out_ref.shape: print(\"The",
"is {0}.\".format(maximal_error)) if maximal_error < 10**(-6): print(\"OK:Output seems to match",
"sys.argv[1] ref_filename = sys.argv[2] f = h5py.File(filename, 'r') ref_f =",
"'r') out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape !=",
"np.array(ref_f['output_data']) if out.shape != out_ref.shape: print(\"The files do not contain",
"as np if len(sys.argv) != 3: print(\"Expected two arguments. Output",
"sys.argv[2] f = h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r') out",
"h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape",
"a reference output. # Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import",
"range(0, 5): print(\"Image\", i) print(\"Expected:\", end=\"\") for j in range(0,",
"len(sys.argv) != 3: print(\"Expected two arguments. Output and reference output",
"compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import h5py import numpy as",
"{0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value",
"sys import h5py import numpy as np if len(sys.argv) !=",
"Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import h5py import",
"for j in range(0, 10): print(out_ref[i, j], end = \"",
"in range(0, 5): print(\"Image\", i) print(\"Expected:\", end=\"\") for j in",
"to match the reference.\") sys.exit(0) print(\"Failure:Output does not match the",
"the reference.\") sys.exit(0) print(\"Failure:Output does not match the reference.\") maximal_error",
"filename = sys.argv[1] ref_filename = sys.argv[2] f = h5py.File(filename, 'r')",
"j in range(0, 10): print(out_ref[i, j], end = \" \")",
"number of outputs.\") print(\"The output size: {0}.\".format(out.shape[0])) print(\"The reference size:",
"= (out_ref - out) / ref_value maximal_error = np.amax(error) print(\"Maximal",
"axis=1) print(maximal_error.shape) for i in range(0, 5): print(\"Image\", i) print(\"Expected:\",",
"\" \") print(\"\\nGot:\", end=\"\") for j in range(0, 10): print(out[i,",
"with a reference output. # Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5",
"script to compare output with a reference output. # Usage:",
"print(\"Expected two arguments. Output and reference output file.\") sys.exit(1) filename",
"!= 3: print(\"Expected two arguments. Output and reference output file.\")",
"error = (out_ref - out) / ref_value maximal_error = np.amax(error)",
"sys.exit(1) filename = sys.argv[1] ref_filename = sys.argv[2] f = h5py.File(filename,",
"maximal_error = np.amax(error) print(\"Maximal error between the output and the",
"ref_value maximal_error = np.amax(error) print(\"Maximal error between the output and",
"print(\"OK:Output seems to match the reference.\") sys.exit(0) print(\"Failure:Output does not",
"f = h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r') out =",
"print(\"Maximal error between the output and the reference is {0}.\".format(maximal_error))",
"= np.array(ref_f['output_data']) if out.shape != out_ref.shape: print(\"The files do not",
"'r') ref_f = h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref =",
"between the output and the reference is {0}.\".format(maximal_error)) if maximal_error",
"np.amax(error) print(\"Maximal error between the output and the reference is",
"np.amax(error, axis=1) print(maximal_error.shape) for i in range(0, 5): print(\"Image\", i)",
"h5py import numpy as np if len(sys.argv) != 3: print(\"Expected",
"for j in range(0, 10): print(out[i, j], end=\" \") print(\"\\nMaximal",
"and reference output file.\") sys.exit(1) filename = sys.argv[1] ref_filename =",
"= h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if",
"of outputs.\") print(\"The output size: {0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0]))",
"output file.\") sys.exit(1) filename = sys.argv[1] ref_filename = sys.argv[2] f",
"range(0, 10): print(out_ref[i, j], end = \" \") print(\"\\nGot:\", end=\"\")",
"output with a reference output. # Usage: python3 compareOutputs.py testOutput.h5",
"sys.exit(0) print(\"Failure:Output does not match the reference.\") maximal_error = np.amax(error,",
"== 0.0] = 1.0 error = (out_ref - out) /",
"import numpy as np if len(sys.argv) != 3: print(\"Expected two",
"print(\"Expected:\", end=\"\") for j in range(0, 10): print(out_ref[i, j], end",
"= np.amax(error) print(\"Maximal error between the output and the reference",
"Simple python3 script to compare output with a reference output.",
"output size: {0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value =",
"and the reference is {0}.\".format(maximal_error)) if maximal_error < 10**(-6): print(\"OK:Output",
"j], end = \" \") print(\"\\nGot:\", end=\"\") for j in",
"reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value == 0.0]",
"\") print(\"\\nGot:\", end=\"\") for j in range(0, 10): print(out[i, j],",
"# Simple python3 script to compare output with a reference",
"python3 script to compare output with a reference output. #",
"maximal_error < 10**(-6): print(\"OK:Output seems to match the reference.\") sys.exit(0)",
"10): print(out[i, j], end=\" \") print(\"\\nMaximal error:\", maximal_error[i], \"\\n\") sys.exit(1)",
"import sys import h5py import numpy as np if len(sys.argv)",
"print(out_ref[i, j], end = \" \") print(\"\\nGot:\", end=\"\") for j",
"the same number of outputs.\") print(\"The output size: {0}.\".format(out.shape[0])) print(\"The",
"= 1.0 error = (out_ref - out) / ref_value maximal_error",
"ref_value[ref_value == 0.0] = 1.0 error = (out_ref - out)",
"reference.\") sys.exit(0) print(\"Failure:Output does not match the reference.\") maximal_error =",
"to compare output with a reference output. # Usage: python3",
"{0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0",
"reference.\") maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for i in range(0,",
"/ ref_value maximal_error = np.amax(error) print(\"Maximal error between the output",
"reference output. # Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys",
"outputs.\") print(\"The output size: {0}.\".format(out.shape[0])) print(\"The reference size: {0}.\".format(out_ref.shape[0])) sys.exit(1)",
"import h5py import numpy as np if len(sys.argv) != 3:",
"j in range(0, 10): print(out[i, j], end=\" \") print(\"\\nMaximal error:\",",
"= \" \") print(\"\\nGot:\", end=\"\") for j in range(0, 10):",
"ref_filename = sys.argv[2] f = h5py.File(filename, 'r') ref_f = h5py.File(ref_filename,",
"- out) / ref_value maximal_error = np.amax(error) print(\"Maximal error between",
"if out.shape != out_ref.shape: print(\"The files do not contain the",
"in range(0, 10): print(out_ref[i, j], end = \" \") print(\"\\nGot:\",",
"h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref",
"file.\") sys.exit(1) filename = sys.argv[1] ref_filename = sys.argv[2] f =",
"= sys.argv[2] f = h5py.File(filename, 'r') ref_f = h5py.File(ref_filename, 'r')",
"in range(0, 10): print(out[i, j], end=\" \") print(\"\\nMaximal error:\", maximal_error[i],",
"i) print(\"Expected:\", end=\"\") for j in range(0, 10): print(out_ref[i, j],",
"match the reference.\") maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for i",
"maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for i in range(0, 5):",
"do not contain the same number of outputs.\") print(\"The output",
"3: print(\"Expected two arguments. Output and reference output file.\") sys.exit(1)",
"two arguments. Output and reference output file.\") sys.exit(1) filename =",
"python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import h5py import numpy",
"out) / ref_value maximal_error = np.amax(error) print(\"Maximal error between the",
"out.shape != out_ref.shape: print(\"The files do not contain the same",
"if maximal_error < 10**(-6): print(\"OK:Output seems to match the reference.\")",
"range(0, 10): print(out[i, j], end=\" \") print(\"\\nMaximal error:\", maximal_error[i], \"\\n\")",
"print(\"Image\", i) print(\"Expected:\", end=\"\") for j in range(0, 10): print(out_ref[i,",
"arguments. Output and reference output file.\") sys.exit(1) filename = sys.argv[1]",
"testRefOutput.h5 import sys import h5py import numpy as np if",
"np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0 error = (out_ref -",
"seems to match the reference.\") sys.exit(0) print(\"Failure:Output does not match",
"!= out_ref.shape: print(\"The files do not contain the same number",
"= np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0 error = (out_ref",
"ref_value = np.copy(out_ref) ref_value[ref_value == 0.0] = 1.0 error =",
"end=\"\") for j in range(0, 10): print(out[i, j], end=\" \")",
"out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape != out_ref.shape:",
"= np.amax(error, axis=1) print(maximal_error.shape) for i in range(0, 5): print(\"Image\",",
"not match the reference.\") maximal_error = np.amax(error, axis=1) print(maximal_error.shape) for",
"print(\"\\nGot:\", end=\"\") for j in range(0, 10): print(out[i, j], end=\"",
"ref_f = h5py.File(ref_filename, 'r') out = np.array(f['output_data']) out_ref = np.array(ref_f['output_data'])",
"out_ref = np.array(ref_f['output_data']) if out.shape != out_ref.shape: print(\"The files do",
"np if len(sys.argv) != 3: print(\"Expected two arguments. Output and",
"if len(sys.argv) != 3: print(\"Expected two arguments. Output and reference",
"the output and the reference is {0}.\".format(maximal_error)) if maximal_error <",
"output. # Usage: python3 compareOutputs.py testOutput.h5 testRefOutput.h5 import sys import",
"not contain the same number of outputs.\") print(\"The output size:",
"1.0 error = (out_ref - out) / ref_value maximal_error =",
"np.array(f['output_data']) out_ref = np.array(ref_f['output_data']) if out.shape != out_ref.shape: print(\"The files",
"size: {0}.\".format(out_ref.shape[0])) sys.exit(1) ref_value = np.copy(out_ref) ref_value[ref_value == 0.0] =",
"= sys.argv[1] ref_filename = sys.argv[2] f = h5py.File(filename, 'r') ref_f"
] |
[
"rest_framework import serializers from .models import Tag class TagSerializer(serializers.ModelSerializer): class",
"from rest_framework import serializers from .models import Tag class TagSerializer(serializers.ModelSerializer):",
"<gh_stars>1-10 # -*- coding: utf-8 -*- from rest_framework import serializers",
"# -*- coding: utf-8 -*- from rest_framework import serializers from",
"from .models import Tag class TagSerializer(serializers.ModelSerializer): class Meta: model =",
"coding: utf-8 -*- from rest_framework import serializers from .models import",
"serializers from .models import Tag class TagSerializer(serializers.ModelSerializer): class Meta: model",
".models import Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag",
"import Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag read_only_fields",
"utf-8 -*- from rest_framework import serializers from .models import Tag",
"-*- from rest_framework import serializers from .models import Tag class",
"Tag class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag read_only_fields =",
"class TagSerializer(serializers.ModelSerializer): class Meta: model = Tag read_only_fields = ('topics_count',)",
"import serializers from .models import Tag class TagSerializer(serializers.ModelSerializer): class Meta:",
"-*- coding: utf-8 -*- from rest_framework import serializers from .models"
] |
[
"if result['status'] == 'ok': print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ is",
"'guest') try: result = API.aliveness_test('/') if result['status'] == 'ok': print(\"RabbitMQ",
"if __name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try:",
"API.aliveness_test('/') if result['status'] == 'ok': print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ",
"% why) except ApiError as why: print('ApiError: %s' % why)",
"amqpstorm.management import ApiError from amqpstorm.management import ManagementApi if __name__ ==",
"from amqpstorm.management import ApiError from amqpstorm.management import ManagementApi if __name__",
"ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result = API.aliveness_test('/') if result['status'] ==",
"amqpstorm.management import ApiConnectionError from amqpstorm.management import ApiError from amqpstorm.management import",
"= ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result = API.aliveness_test('/') if result['status']",
"print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ is not alive! :(\") except",
"from amqpstorm.management import ApiConnectionError from amqpstorm.management import ApiError from amqpstorm.management",
"Error: %s' % why) except ApiError as why: print('ApiError: %s'",
"except ApiConnectionError as why: print('Connection Error: %s' % why) except",
"'ok': print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ is not alive! :(\")",
"amqpstorm.management import ManagementApi if __name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672',",
":(\") except ApiConnectionError as why: print('Connection Error: %s' % why)",
"== '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result =",
"ApiConnectionError as why: print('Connection Error: %s' % why) except ApiError",
"%s' % why) except ApiError as why: print('ApiError: %s' %",
"alive! :(\") except ApiConnectionError as why: print('Connection Error: %s' %",
"import ApiConnectionError from amqpstorm.management import ApiError from amqpstorm.management import ManagementApi",
"why: print('Connection Error: %s' % why) except ApiError as why:",
"alive!\") else: print(\"RabbitMQ is not alive! :(\") except ApiConnectionError as",
"import ApiError from amqpstorm.management import ManagementApi if __name__ == '__main__':",
"print(\"RabbitMQ is not alive! :(\") except ApiConnectionError as why: print('Connection",
"as why: print('Connection Error: %s' % why) except ApiError as",
"'__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result = API.aliveness_test('/')",
"ApiConnectionError from amqpstorm.management import ApiError from amqpstorm.management import ManagementApi if",
"'guest', 'guest') try: result = API.aliveness_test('/') if result['status'] == 'ok':",
"else: print(\"RabbitMQ is not alive! :(\") except ApiConnectionError as why:",
"ManagementApi if __name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest')",
"not alive! :(\") except ApiConnectionError as why: print('Connection Error: %s'",
"ApiError from amqpstorm.management import ManagementApi if __name__ == '__main__': API",
"is not alive! :(\") except ApiConnectionError as why: print('Connection Error:",
"API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result = API.aliveness_test('/') if",
"<gh_stars>0 from amqpstorm.management import ApiConnectionError from amqpstorm.management import ApiError from",
"= API.aliveness_test('/') if result['status'] == 'ok': print(\"RabbitMQ is alive!\") else:",
"from amqpstorm.management import ManagementApi if __name__ == '__main__': API =",
"import ManagementApi if __name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest',",
"result = API.aliveness_test('/') if result['status'] == 'ok': print(\"RabbitMQ is alive!\")",
"result['status'] == 'ok': print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ is not",
"is alive!\") else: print(\"RabbitMQ is not alive! :(\") except ApiConnectionError",
"print('Connection Error: %s' % why) except ApiError as why: print('ApiError:",
"== 'ok': print(\"RabbitMQ is alive!\") else: print(\"RabbitMQ is not alive!",
"__name__ == '__main__': API = ManagementApi('http://127.0.0.1:15672', 'guest', 'guest') try: result",
"try: result = API.aliveness_test('/') if result['status'] == 'ok': print(\"RabbitMQ is"
] |
[
"= True df = em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False) df_other",
"zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import",
"= df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south,",
"utf-8 -*- from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder",
"provider = \"em\" data_schema = Stockhk def run(self): df_south =",
"df = df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False",
"Stockhk from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider = \"em\"",
"df_south[\"south\"] = True df = em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False)",
"coding: utf-8 -*- from zvt.contract.api import df_to_db from zvt.contract.recorder import",
"data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__ ==",
"\"__main__\": recorder = EMStockhkRecorder() recorder.run() # the __all__ is generated",
"df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema,",
"df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True df = em_api.get_tradable_list(entity_type=\"stockhk\") df =",
"class EMStockhkRecorder(Recorder): provider = \"em\" data_schema = Stockhk def run(self):",
"zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider = \"em\" data_schema =",
"def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\", drop=False)",
"hk_south=True) df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True df =",
"EMStockhkRecorder() recorder.run() # the __all__ is generated __all__ = [\"EMStockhkRecorder\"]",
"df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__",
"force_update=self.force_update) if __name__ == \"__main__\": recorder = EMStockhkRecorder() recorder.run() #",
"from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder):",
"import df_to_db from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk",
"provider=self.provider, force_update=self.force_update) if __name__ == \"__main__\": recorder = EMStockhkRecorder() recorder.run()",
"df_to_db from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from",
"provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__ == \"__main__\":",
"import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api",
"= em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True",
"Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api class",
"df = em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy()",
"Stockhk def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\",",
"data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__ == \"__main__\": recorder = EMStockhkRecorder()",
"= df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other,",
"\"em\" data_schema = Stockhk def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True)",
"import Stockhk from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider =",
"zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider",
"zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import",
"df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True df = em_api.get_tradable_list(entity_type=\"stockhk\")",
"True df = em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False) df_other =",
"from zvt.recorders.em import em_api class EMStockhkRecorder(Recorder): provider = \"em\" data_schema",
"from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta import Stockhk from zvt.recorders.em",
"-*- from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from",
"= em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"]",
"-*- coding: utf-8 -*- from zvt.contract.api import df_to_db from zvt.contract.recorder",
"recorder = EMStockhkRecorder() recorder.run() # the __all__ is generated __all__",
"= df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True df = em_api.get_tradable_list(entity_type=\"stockhk\") df",
"data_schema = Stockhk def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south",
"= \"em\" data_schema = Stockhk def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\",",
"from zvt.contract.api import df_to_db from zvt.contract.recorder import Recorder from zvt.domain.meta.stockhk_meta",
"= Stockhk def run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south =",
"run(self): df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"]",
"df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema,",
"df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider,",
"if __name__ == \"__main__\": recorder = EMStockhkRecorder() recorder.run() # the",
"__name__ == \"__main__\": recorder = EMStockhkRecorder() recorder.run() # the __all__",
"= EMStockhkRecorder() recorder.run() # the __all__ is generated __all__ =",
"df_south = em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"] =",
"em_api.get_tradable_list(entity_type=\"stockhk\", hk_south=True) df_south = df_south.set_index(\"code\", drop=False) df_south[\"south\"] = True df",
"drop=False) df_south[\"south\"] = True df = em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\",",
"em_api class EMStockhkRecorder(Recorder): provider = \"em\" data_schema = Stockhk def",
"drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider,",
"= False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)",
"df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] = False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update)",
"False df_to_db(df=df_south, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if",
"import em_api class EMStockhkRecorder(Recorder): provider = \"em\" data_schema = Stockhk",
"EMStockhkRecorder(Recorder): provider = \"em\" data_schema = Stockhk def run(self): df_south",
"em_api.get_tradable_list(entity_type=\"stockhk\") df = df.set_index(\"code\", drop=False) df_other = df.loc[~df.index.isin(df_south.index)].copy() df_other[\"south\"] =",
"force_update=self.force_update) df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__ == \"__main__\": recorder",
"df_to_db(df=df_other, data_schema=self.data_schema, provider=self.provider, force_update=self.force_update) if __name__ == \"__main__\": recorder =",
"== \"__main__\": recorder = EMStockhkRecorder() recorder.run() # the __all__ is",
"# -*- coding: utf-8 -*- from zvt.contract.api import df_to_db from"
] |
[
"sample_width, sample_height) # handle data of control groups control_0h_summary =",
"= [] for group in sd_groups: x_index = 0 y_index",
"= setting[\"24h_datafile\"] # sample width and height are the size",
"int(sample_width / basic_width) x_data = [] current_concentration = initial_concentration for",
"= calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST =",
"number of each control group control_number_list = setting[\"control_number\"] # output",
"initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape data into",
"= np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group in sd_groups: x_index",
"in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample \"",
"setting[\"output_directory\"] # import initial concentration and calculate x_data initial_concentration =",
"x_sampling, y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer) # draw the",
"group control_number_list = setting[\"control_number\"] # output directory output_directory = setting[\"output_directory\"]",
"csv_writer_grouped.writerow(\"\") sample_num = 0 for SAMPLE in FULL_RESULT_LIST: SAMPLE =",
"import initial concentration and calculate x_data initial_concentration = setting[\"initial_concentration\"] repeat_times",
"setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] # sample width and height are",
"= np.array(sd_matrix) # split array into different samples sd_groups =",
"average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)])",
"control_0h_summary = 0 for number in control_number_list: number = number",
"of each control group control_number_list = setting[\"control_number\"] # output directory",
"x_data = [] current_concentration = initial_concentration for i in range(repeat_times):",
"in file of ./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"]",
"handle data of control groups control_0h_summary = 0 for number",
"= sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary",
"data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width,",
"for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg,",
"0 for number in control_number_list: number = number - 1",
"x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index]) index +=",
"y_index += 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST,",
"FULL_RESULT_LIST: sample_num += 1 fig, ax = plt.subplots() index =",
"concentration and calculate x_data initial_concentration = setting[\"initial_concentration\"] repeat_times = int(sample_width",
"control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width * sample_height",
"'green', 'cyan', 'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST = []",
"new_line = [] for element in line: sd_data = (float(element)",
"0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory +",
"final_sd_data = read_24h_data() # reshape data into the size of",
"control groups control_0h_summary = 0 for number in control_number_list: number",
"in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5,",
"setting[\"24h_datafile\"] # sample width and height are the size of",
"= setting[\"dilution_protocol\"] # width of each dilution basic_width = setting[\"basic_width\"]",
"np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg = []",
"[] for group in sd_groups: x_index = 0 y_index =",
"[] current_concentration = initial_concentration for i in range(repeat_times): x_data.append(current_concentration) current_concentration",
"= setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] # width",
"group in sd_groups: x_index = 0 y_index = 0 sample_buffer",
"new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split array into different",
"= [] x_index += 1 y_index += 1 x_index =",
"height are the size of each sample area sample_width =",
"# output grouped result output_f_grouped = open(\"./output/\" + output_directory +",
"for SAMPLE in FULL_RESULT_LIST: sample_num += 1 fig, ax =",
"EC50_AVG_LIST.append(avg) # draw the average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer",
"csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\" + output_directory +",
"= [] EC50_AVG_LIST = [] sample_num = 0 for SAMPLE",
"basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index += 1 y_index +=",
"= setting[\"initial_concentration\"] repeat_times = int(sample_width / basic_width) x_data = []",
"grid sd_matrix = [] for line in rebuild_24h_data: new_line =",
"[] while y_index < sample_height: while x_index < basic_width: x",
"\"/Sample \" + str(sample_num)) plt.cla() plt.close(fig) # output grouped result",
"concentration: \" + str(initial_concentration), \"dilution protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\")",
"* sample_height * len(control_number_list)) control_24h_summary = 0 for number in",
"number - 1 sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary +",
"x = x_index while x < sample_width: data_buffer.append(group[y_index][x]) x +=",
"control_0h_average.item()) \\ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix =",
"open(\"./output/\" + output_directory + \"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full) for",
"./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] # sample width",
"x_buffer = [] x_sampling_buffer = [] y_sampling_buffer = [] for",
"= [] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in",
"color='black') plt.savefig(\"./output/\" + output_directory + \"/figs\" + \"/Sample \" +",
"= plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer = []",
"in control_number_list: number = number - 1 sample = sample_divided_list_0h[number]",
"sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split array into different samples",
"deviation of each grid sd_matrix = [] for line in",
"file of ./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] #",
"[] x_index += 1 y_index += 1 x_index = 0",
"control_0h_average = control_0h_summary / (sample_width * sample_height * len(control_number_list)) control_24h_summary",
"as np import csv setting = read_setting_json() setting = setting[\"rule\"]",
"y, x_sampling, y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer) # draw",
"index += 1 EC50_LIST.append(x_buffer) # draw the average result avg",
"np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average curve x_sampling_buffer = np.array(x_sampling_buffer).T",
"for line in rebuild_24h_data: new_line = [] for element in",
"+ output_directory + \"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full) for line",
"+ \"/figs\" + \"/Sample \" + str(sample_num)) plt.cla() plt.close(fig) #",
"RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group in",
"line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg,",
"sample_num = 0 for SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T",
"= np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg = [] for line",
"+ \"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full) for line in sd_matrix:",
"sd_matrix = [] for line in rebuild_24h_data: new_line = []",
"line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg,",
"= [] y_sampling_buffer = [] for repeat in SAMPLE: x,",
"final_filename = setting[\"24h_datafile\"] # sample width and height are the",
"in sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST =",
"+ calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width * sample_height *",
"[] for sample in sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width)",
"csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration), \"dilution protocol: \" +",
"sample in sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST",
"'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST =",
"grouped result output_f_grouped = open(\"./output/\" + output_directory + \"/result_grouped.csv\", \"w\")",
"basic_width = setting[\"basic_width\"] # number of each control group control_number_list",
"and height are the size of each sample area sample_width",
"\\ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix)",
"EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\" +",
"np import csv setting = read_setting_json() setting = setting[\"rule\"] #",
"sample width and height are the size of each sample",
"csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\")",
"= int(sample_width / basic_width) x_data = [] current_concentration = initial_concentration",
"data into the size of board rebuild_0h_data = initial_sd_data.reshape((32, -1))",
"+ output_directory + \"/figs\" + \"/Sample \" + str(sample_num)) plt.cla()",
"- 1 sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample)",
"x_index = 0 y_index = 0 sample_buffer = [] data_buffer",
"FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange', 'yellow', 'green',",
"= np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg =",
"= control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width *",
"control_number_list = setting[\"control_number\"] # output directory output_directory = setting[\"output_directory\"] #",
"y_index < sample_height: while x_index < basic_width: x = x_index",
"= setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] # sample width and height",
"np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\" + output_directory + \"/result_full.csv\",",
"the average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the",
"= 0 for SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num",
"sample_num += 1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for repeat in",
"len(control_number_list)) control_24h_summary = 0 for number in control_number_list: number =",
"x < sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer =",
"\"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\" + output_directory",
"each dilution basic_width = setting[\"basic_width\"] # number of each control",
"numpy as np import csv setting = read_setting_json() setting =",
"array into different samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups",
"= number - 1 sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary",
"for i in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol # load",
"matplotlib.pyplot as plt import numpy as np import csv setting",
"result output_f_grouped = open(\"./output/\" + output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped",
"the size of each sample area sample_width = setting[\"sample_width\"] sample_height",
"control_24h_summary = 0 for number in control_number_list: number = number",
"read_0h_data() final_sd_data = read_24h_data() # reshape data into the size",
"optional_color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST",
"in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol # load raw data",
"basic_width: x = x_index while x < sample_width: data_buffer.append(group[y_index][x]) x",
"sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary /",
"line: sd_data = (float(element) - control_0h_average.item()) \\ / (control_24h_average.item() -",
"/ (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) #",
"plt.close(fig) # output grouped result output_f_grouped = open(\"./output/\" + output_directory",
"for sample in sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result)",
"sample_height: while x_index < basic_width: x = x_index while x",
"0 ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer = [] y_sampling_buffer",
"in rebuild_24h_data: new_line = [] for element in line: sd_data",
"of control groups control_0h_summary = 0 for number in control_number_list:",
"group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data,",
"split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot",
"number = number - 1 sample = sample_divided_list_0h[number] control_0h_summary =",
"setting[\"dilution_protocol\"] # width of each dilution basic_width = setting[\"basic_width\"] #",
"= csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration), \"dilution protocol: \"",
"into the size of board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data",
"sample_height = setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] # width of each",
"= [] for sample in sd_groups: result = calculate_avg_of_sample(sample, sample_width,",
"= control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width *",
"draw the average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw",
"split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST = []",
"size of each sample area sample_width = setting[\"sample_width\"] sample_height =",
"of each dilution basic_width = setting[\"basic_width\"] # number of each",
"optional_color[index]) index += 1 EC50_LIST.append(x_buffer) # draw the average result",
"calculate standard deviation of each grid sd_matrix = [] for",
"output_f_full = open(\"./output/\" + output_directory + \"/result_full.csv\", \"w\") csv_writer_full =",
"output grouped result output_f_grouped = open(\"./output/\" + output_directory + \"/result_grouped.csv\",",
"x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg",
"dtype=float) optional_color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple']",
"open(\"./output/\" + output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial",
"= np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\")",
"\"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration),",
"data into a 2-dimensional array contains each group data sample_divided_list_0h",
"fig, ax = plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer",
"# number of each control group control_number_list = setting[\"control_number\"] #",
"line in rebuild_24h_data: new_line = [] for element in line:",
"of ./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] # sample",
"# load raw data initial_sd_data = read_0h_data() final_sd_data = read_24h_data()",
"= initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape data",
"protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0 for SAMPLE",
"for SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num += 1",
"[] data_buffer = [] while y_index < sample_height: while x_index",
"= 0 ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer = []",
"[] sample_num = 0 for SAMPLE in FULL_RESULT_LIST: sample_num +=",
"x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling)",
"# handle data of control groups control_0h_summary = 0 for",
"x_data initial_concentration = setting[\"initial_concentration\"] repeat_times = int(sample_width / basic_width) x_data",
"of board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1))",
"data_buffer = [] x_index += 1 y_index += 1 x_index",
"width and height are the size of each sample area",
"control_0h_summary / (sample_width * sample_height * len(control_number_list)) control_24h_summary = 0",
"= [] for element in line: sd_data = (float(element) -",
"1 sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average",
"calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt import numpy as np",
"x_index += 1 y_index += 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer)",
"# reshape data into a 2-dimensional array contains each group",
"number = number - 1 sample = sample_divided_list_24h[number] control_24h_summary =",
"1 fig, ax = plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num))",
"split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data of control groups control_0h_summary",
"(sample_width * sample_height * len(control_number_list)) control_24h_summary = 0 for number",
"of each sample area sample_width = setting[\"sample_width\"] sample_height = setting[\"sample_height\"]",
"setting[\"basic_width\"] # number of each control group control_number_list = setting[\"control_number\"]",
"for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1])",
"control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width * sample_height",
"initial_concentration for i in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol #",
"0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange',",
"setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] # width of",
"dilution_protocol # load raw data initial_sd_data = read_0h_data() final_sd_data =",
"result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average curve",
"= 0 for number in control_number_list: number = number -",
"# calculate standard deviation of each grid sd_matrix = []",
"EC50_LIST.append(x_buffer) # draw the average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg)",
"number in control_number_list: number = number - 1 sample =",
"np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg = [] for line in",
"= setting[\"basic_width\"] # number of each control group control_number_list =",
"for group in sd_groups: x_index = 0 y_index = 0",
"initial_filename = setting[\"0h_datafile\"] final_filename = setting[\"24h_datafile\"] # sample width and",
"* len(control_number_list)) control_24h_summary = 0 for number in control_number_list: number",
"FULL_RESULT_LIST = [] for group in sd_groups: x_index = 0",
"sample_width = setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] #",
"+= basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index += 1 y_index",
"for number in control_number_list: number = number - 1 sample",
"calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width * sample_height * len(control_number_list))",
"\" + str(initial_concentration), \"dilution protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num",
"= control_24h_summary / (sample_width * sample_height * len(control_number_list)) # calculate",
"output_f_grouped.close() output_f_full = open(\"./output/\" + output_directory + \"/result_full.csv\", \"w\") csv_writer_full",
"+ output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration:",
"sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average =",
"x_data.append(current_concentration) current_concentration /= dilution_protocol # load raw data initial_sd_data =",
"= number - 1 sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary",
"a 2-dimensional array contains each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data,",
"sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data",
"/ (sample_width * sample_height * len(control_number_list)) # calculate standard deviation",
"repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index])",
"avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average curve x_sampling_buffer",
"y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer) # draw the average",
"+ \"/Sample \" + str(sample_num)) plt.cla() plt.close(fig) # output grouped",
"csv setting = read_setting_json() setting = setting[\"rule\"] # load experiment",
"/ basic_width) x_data = [] current_concentration = initial_concentration for i",
"x_sampling_buffer = [] y_sampling_buffer = [] for repeat in SAMPLE:",
"# load experiment parameter # experiment parameter is stored in",
"\" + str(sample_num)) plt.cla() plt.close(fig) # output grouped result output_f_grouped",
"SAMPLE in FULL_RESULT_LIST: sample_num += 1 fig, ax = plt.subplots()",
"draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import",
"0 for SAMPLE in FULL_RESULT_LIST: sample_num += 1 fig, ax",
"= split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST =",
"sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data of",
"setting = setting[\"rule\"] # load experiment parameter # experiment parameter",
"(sample_width * sample_height * len(control_number_list)) # calculate standard deviation of",
"FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange', 'yellow',",
"split array into different samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height)",
"# reshape data into the size of board rebuild_0h_data =",
"import read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample,",
"# import initial concentration and calculate x_data initial_concentration = setting[\"initial_concentration\"]",
"= (float(element) - control_0h_average.item()) \\ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data)",
"x_sampling_avg = [] y_sampling_avg = [] for line in x_sampling_buffer:",
"= setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] # width of each dilution",
"csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\" + output_directory + \"/result_full.csv\", \"w\")",
"y_sampling_buffer = [] for repeat in SAMPLE: x, y, x_sampling,",
"= setting[\"output_directory\"] # import initial concentration and calculate x_data initial_concentration",
"import numpy as np import csv setting = read_setting_json() setting",
"\" + str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list",
"/ (sample_width * sample_height * len(control_number_list)) control_24h_summary = 0 for",
"= 0 sample_buffer = [] data_buffer = [] while y_index",
"x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black')",
"average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average",
"= read_setting_json() setting = setting[\"rule\"] # load experiment parameter #",
"number - 1 sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary +",
"in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black')",
"np.array(sd_matrix) # split array into different samples sd_groups = split_array_into_samples(sd_matrix,",
"SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample",
"experiment parameter is stored in file of ./data/setting.json initial_filename =",
"[] for element in line: sd_data = (float(element) - control_0h_average.item())",
"read_0h_data, read_24h_data, draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from",
"and calculate x_data initial_concentration = setting[\"initial_concentration\"] repeat_times = int(sample_width /",
"str(sample_num)) plt.cla() plt.close(fig) # output grouped result output_f_grouped = open(\"./output/\"",
"sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average =",
"element in line: sd_data = (float(element) - control_0h_average.item()) \\ /",
"sample_height) # handle data of control groups control_0h_summary = 0",
"<reponame>yanwunhao/auto-mshts from util.io import read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert",
"# experiment parameter is stored in file of ./data/setting.json initial_filename",
"sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST = [] for sample in",
"control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width",
"# split array into different samples sd_groups = split_array_into_samples(sd_matrix, sample_width,",
"= [] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 =",
"= final_sd_data.reshape((32, -1)) # reshape data into a 2-dimensional array",
"y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index]) index += 1",
"[] EC50_AVG_LIST = [] sample_num = 0 for SAMPLE in",
"x_index while x < sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer)",
"+= 1 fig, ax = plt.subplots() index = 0 ax.set_title('Sample",
"color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory + \"/figs\" +",
"csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration), \"dilution protocol: \" + str(dilution_protocol)])",
"= sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary",
"each sample area sample_width = setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol",
"initial_sd_data = read_0h_data() final_sd_data = read_24h_data() # reshape data into",
"into different samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups =",
"csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full = open(\"./output/\"",
"repeat in SAMPLE: x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat)",
"np.array(sd_groups, dtype=float) RESULT_LIST = [] for sample in sd_groups: result",
"+ \"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" +",
"repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = [] for ec50_index",
"stored in file of ./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename =",
"sample area sample_width = setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol =",
"= setting[\"rule\"] # load experiment parameter # experiment parameter is",
"sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST",
"x_index < basic_width: x = x_index while x < sample_width:",
"= SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for",
"'+str(sample_num)) x_buffer = [] x_sampling_buffer = [] y_sampling_buffer = []",
"EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\",",
"dilution basic_width = setting[\"basic_width\"] # number of each control group",
"x, y, x_sampling, y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer) #",
"sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST = [] for sample",
"'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST = [] sample_num =",
"ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([])",
"y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory + \"/figs\" + \"/Sample \"",
"= read_24h_data() # reshape data into the size of board",
"[] y_sampling_buffer = [] for repeat in SAMPLE: x, y,",
"sample_num += 1 fig, ax = plt.subplots() index = 0",
"parameter # experiment parameter is stored in file of ./data/setting.json",
"# draw the average result avg = np.mean(x_buffer) EC50_AVG_LIST.append(avg) #",
"curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = []",
"output_f_grouped = open(\"./output/\" + output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped =",
"'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory + \"/figs\"",
"# output directory output_directory = setting[\"output_directory\"] # import initial concentration",
"sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index",
"are the size of each sample area sample_width = setting[\"sample_width\"]",
"ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory + \"/figs\" + \"/Sample",
"x += basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index += 1",
"while x_index < basic_width: x = x_index while x <",
"data initial_sd_data = read_0h_data() final_sd_data = read_24h_data() # reshape data",
"different samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups,",
"['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST = []",
"x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o',",
"ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"])",
"sample_height * len(control_number_list)) # calculate standard deviation of each grid",
"from util.io import read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert import",
"EC50_AVG_LIST = [] sample_num = 0 for SAMPLE in FULL_RESULT_LIST:",
"standard deviation of each grid sd_matrix = [] for line",
"util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve",
"+= 1 EC50_LIST.append(x_buffer) # draw the average result avg =",
"= open(\"./output/\" + output_directory + \"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full)",
"csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration), \"dilution protocol:",
"+ str(sample_num)) plt.cla() plt.close(fig) # output grouped result output_f_grouped =",
"\"/figs\" + \"/Sample \" + str(sample_num)) plt.cla() plt.close(fig) # output",
"rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape",
"util.io import read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert import split_array_into_samples,",
"\" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0 for SAMPLE in",
"= control_0h_summary / (sample_width * sample_height * len(control_number_list)) control_24h_summary =",
"np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group in sd_groups: x_index =",
"in FULL_RESULT_LIST: sample_num += 1 fig, ax = plt.subplots() index",
"y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" +",
"from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample,",
"import matplotlib.pyplot as plt import numpy as np import csv",
"size of board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32,",
"convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt",
"= initial_concentration for i in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol",
"x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index]) index",
"calculate x_data initial_concentration = setting[\"initial_concentration\"] repeat_times = int(sample_width / basic_width)",
"* sample_height * len(control_number_list)) # calculate standard deviation of each",
"output_directory + \"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full) for line in",
"reshape data into the size of board rebuild_0h_data = initial_sd_data.reshape((32,",
"directory output_directory = setting[\"output_directory\"] # import initial concentration and calculate",
"= [] x_sampling_buffer = [] y_sampling_buffer = [] for repeat",
"result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST",
"sd_data = (float(element) - control_0h_average.item()) \\ / (control_24h_average.item() - control_0h_average.item())",
"basic_width) x_data = [] current_concentration = initial_concentration for i in",
"= np.array(sd_groups, dtype=float) RESULT_LIST = [] for sample in sd_groups:",
"in line: sd_data = (float(element) - control_0h_average.item()) \\ / (control_24h_average.item()",
"str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0 for SAMPLE in FULL_RESULT_LIST: SAMPLE",
"+= 1 y_index += 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST",
"# draw the average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer =",
"plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer",
"= setting[\"control_number\"] # output directory output_directory = setting[\"output_directory\"] # import",
"# sample width and height are the size of each",
"output_directory = setting[\"output_directory\"] # import initial concentration and calculate x_data",
"into a 2-dimensional array contains each group data sample_divided_list_0h =",
"in SAMPLE: x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x)",
"y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax,",
"(float(element) - control_0h_average.item()) \\ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line)",
"repeat_times = int(sample_width / basic_width) x_data = [] current_concentration =",
"ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer = [] y_sampling_buffer =",
"final_sd_data.reshape((32, -1)) # reshape data into a 2-dimensional array contains",
"control_number_list: number = number - 1 sample = sample_divided_list_0h[number] control_0h_summary",
"= [] for repeat in SAMPLE: x, y, x_sampling, y_sampling",
"= [] y_sampling_avg = [] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line))",
"1 EC50_LIST.append(x_buffer) # draw the average result avg = np.mean(x_buffer)",
"plt import numpy as np import csv setting = read_setting_json()",
"\"w\") csv_writer_full = csv.writer(output_f_full) for line in sd_matrix: csv_writer_full.writerow(line) output_f_full.close()",
"'purple'] EC50_LIST = [] EC50_AVG_LIST = [] sample_num = 0",
"'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST",
"str(initial_concentration), \"dilution protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0",
"range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol # load raw data initial_sd_data",
"y_sampling_buffer: y_sampling_avg.append(np.mean(line)) ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\"",
"sample_buffer.append(data_buffer) data_buffer = [] x_index += 1 y_index += 1",
"EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full",
"- 1 sample = sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample)",
"initial_concentration = setting[\"initial_concentration\"] repeat_times = int(sample_width / basic_width) x_data =",
"draw the average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T",
"< basic_width: x = x_index while x < sample_width: data_buffer.append(group[y_index][x])",
"sample_buffer = [] data_buffer = [] while y_index < sample_height:",
"plt.cla() plt.close(fig) # output grouped result output_f_grouped = open(\"./output/\" +",
"csv_writer_full = csv.writer(output_f_full) for line in sd_matrix: csv_writer_full.writerow(line) output_f_full.close() print(\"Finished\")",
"control_24h_summary / (sample_width * sample_height * len(control_number_list)) # calculate standard",
"data of control groups control_0h_summary = 0 for number in",
"RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group in sd_groups:",
"setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"] # width of each dilution basic_width",
"calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = []",
"= x_index while x < sample_width: data_buffer.append(group[y_index][x]) x += basic_width",
"parameter is stored in file of ./data/setting.json initial_filename = setting[\"0h_datafile\"]",
"+ calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width * sample_height *",
"1 sample = sample_divided_list_0h[number] control_0h_summary = control_0h_summary + calculate_summary_of_sample(sample) control_0h_average",
"0 y_index = 0 sample_buffer = [] data_buffer = []",
"str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = []",
"experiment parameter # experiment parameter is stored in file of",
"x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color =",
"y_sampling_avg = [] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line",
"1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat)",
"read_24h_data, draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus",
"output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \"",
"fit_sigmoid_curve import matplotlib.pyplot as plt import numpy as np import",
"[] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer:",
"< sample_height: while x_index < basic_width: x = x_index while",
"\"dilution protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0 for",
"+= 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float)",
"np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange', 'yellow', 'green', 'cyan', 'blue',",
"= ['red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple'] EC50_LIST =",
"contains each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h",
"index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer = [] x_sampling_buffer =",
"= fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling,",
"basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = [] for group",
"reshape data into a 2-dimensional array contains each group data",
"= [] while y_index < sample_height: while x_index < basic_width:",
"plt.savefig(\"./output/\" + output_directory + \"/figs\" + \"/Sample \" + str(sample_num))",
"+ str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num = 0 for SAMPLE in FULL_RESULT_LIST:",
"in sd_groups: x_index = 0 y_index = 0 sample_buffer =",
"control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary / (sample_width",
"current_concentration = initial_concentration for i in range(repeat_times): x_data.append(current_concentration) current_concentration /=",
"for element in line: sd_data = (float(element) - control_0h_average.item()) \\",
"= 0 for SAMPLE in FULL_RESULT_LIST: sample_num += 1 fig,",
"= [] current_concentration = initial_concentration for i in range(repeat_times): x_data.append(current_concentration)",
"FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample \" +",
"= 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red',",
"dilution_protocol = setting[\"dilution_protocol\"] # width of each dilution basic_width =",
"in control_number_list: number = number - 1 sample = sample_divided_list_24h[number]",
"sd_matrix = np.array(sd_matrix) # split array into different samples sd_groups",
"= np.array(FULL_RESULT_LIST, dtype=float) optional_color = ['red', 'orange', 'yellow', 'green', 'cyan',",
"sd_groups: x_index = 0 y_index = 0 sample_buffer = []",
"for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = [] for",
"control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split array into",
"np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close()",
"1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST = np.array(FULL_RESULT_LIST, dtype=float) optional_color",
"y_index = 0 sample_buffer = [] data_buffer = [] while",
"/= dilution_protocol # load raw data initial_sd_data = read_0h_data() final_sd_data",
"output directory output_directory = setting[\"output_directory\"] # import initial concentration and",
"rebuild_24h_data: new_line = [] for element in line: sd_data =",
"= 0 y_index = 0 sample_buffer = [] data_buffer =",
"each grid sd_matrix = [] for line in rebuild_24h_data: new_line",
"0 for SAMPLE in FULL_RESULT_LIST: SAMPLE = SAMPLE.T sample_num +=",
"while x < sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer",
"sample_height * len(control_number_list)) control_24h_summary = 0 for number in control_number_list:",
"y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg = [] y_sampling_avg = [] for",
"control_24h_average = control_24h_summary / (sample_width * sample_height * len(control_number_list)) #",
"EC50_LIST = [] EC50_AVG_LIST = [] sample_num = 0 for",
"[] x_sampling_buffer = [] y_sampling_buffer = [] for repeat in",
"\"w\") csv_writer_grouped = csv.writer(output_f_grouped) csv_writer_grouped.writerow([\"initial concentration: \" + str(initial_concentration), \"dilution",
"sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST) FULL_RESULT_LIST = [] for",
"import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import",
"0 sample_buffer = [] data_buffer = [] while y_index <",
"current_concentration /= dilution_protocol # load raw data initial_sd_data = read_0h_data()",
"- control_0h_average.item()) \\ / (control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix",
"dtype=float) RESULT_LIST = [] for sample in sd_groups: result =",
"data_buffer = [] while y_index < sample_height: while x_index <",
"SAMPLE: x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling)",
"setting[\"control_number\"] # output directory output_directory = setting[\"output_directory\"] # import initial",
"in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = [] for ec50_index in",
"split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle",
"average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg =",
"is stored in file of ./data/setting.json initial_filename = setting[\"0h_datafile\"] final_filename",
"ec50_result_list = [] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50",
"sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float) RESULT_LIST = [] for",
"from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt import",
"y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y,",
"i in range(repeat_times): x_data.append(current_concentration) current_concentration /= dilution_protocol # load raw",
"setting[\"rule\"] # load experiment parameter # experiment parameter is stored",
"read_24h_data() # reshape data into the size of board rebuild_0h_data",
"calculate_summary_of_sample(sample) control_0h_average = control_0h_summary / (sample_width * sample_height * len(control_number_list))",
"load experiment parameter # experiment parameter is stored in file",
"csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50, np.std(ec50_result_list)]) csv_writer_grouped.writerow(\"\") output_f_grouped.close() output_f_full =",
"+= 1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for repeat in SAMPLE:",
"[] y_sampling_avg = [] for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for",
"* len(control_number_list)) # calculate standard deviation of each grid sd_matrix",
"read_setting_json() setting = setting[\"rule\"] # load experiment parameter # experiment",
"x_sampling, y_sampling = fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x,",
"width of each dilution basic_width = setting[\"basic_width\"] # number of",
"control group control_number_list = setting[\"control_number\"] # output directory output_directory =",
"csv_writer_grouped.writerow(\"\") ec50_result_list = [] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list)",
"raw data initial_sd_data = read_0h_data() final_sd_data = read_24h_data() # reshape",
"initial concentration and calculate x_data initial_concentration = setting[\"initial_concentration\"] repeat_times =",
"len(control_number_list)) # calculate standard deviation of each grid sd_matrix =",
"groups control_0h_summary = 0 for number in control_number_list: number =",
"(control_24h_average.item() - control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split",
"= split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data of control groups",
"sd_groups: result = calculate_avg_of_sample(sample, sample_width, basic_width) RESULT_LIST.append(result) RESULT_LIST = np.array(RESULT_LIST)",
"SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = [] for ec50_index in EC50_LIST[sample_num-1]:",
"as plt import numpy as np import csv setting =",
"samples sd_groups = split_array_into_samples(sd_matrix, sample_width, sample_height) sd_groups = np.array(sd_groups, dtype=float)",
"csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list = [] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index)",
"fit_sigmoid_curve(x_data, repeat) x_buffer.append(x) x_sampling_buffer.append(x_sampling) y_sampling_buffer.append(y_sampling) draw_single_curve(ax, x, y, x_sampling, y_sampling,",
"setting[\"initial_concentration\"] repeat_times = int(sample_width / basic_width) x_data = [] current_concentration",
"read_setting_json, read_0h_data, read_24h_data, draw_single_curve from util.convert import split_array_into_samples, calculate_avg_of_sample, convert_to_percentage",
"= [] for line in rebuild_24h_data: new_line = [] for",
"rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape data into a 2-dimensional",
"= open(\"./output/\" + output_directory + \"/result_grouped.csv\", \"w\") csv_writer_grouped = csv.writer(output_f_grouped)",
"load raw data initial_sd_data = read_0h_data() final_sd_data = read_24h_data() #",
"= split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) #",
"SAMPLE = SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)])",
"area sample_width = setting[\"sample_width\"] sample_height = setting[\"sample_height\"] dilution_protocol = setting[\"dilution_protocol\"]",
"'cyan', 'blue', 'purple'] EC50_LIST = [] EC50_AVG_LIST = [] sample_num",
"the average curve x_sampling_buffer = np.array(x_sampling_buffer).T y_sampling_buffer = np.array(y_sampling_buffer).T x_sampling_avg",
"import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt import numpy as",
"\"/result_full.csv\", \"w\") csv_writer_full = csv.writer(output_f_full) for line in sd_matrix: csv_writer_full.writerow(line)",
"[] for repeat in SAMPLE: x, y, x_sampling, y_sampling =",
"# width of each dilution basic_width = setting[\"basic_width\"] # number",
"ax = plt.subplots() index = 0 ax.set_title('Sample '+str(sample_num)) x_buffer =",
"each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h =",
"import csv setting = read_setting_json() setting = setting[\"rule\"] # load",
"each control group control_number_list = setting[\"control_number\"] # output directory output_directory",
"= [] sample_num = 0 for SAMPLE in FULL_RESULT_LIST: sample_num",
"= [] data_buffer = [] while y_index < sample_height: while",
"array contains each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height)",
"the size of board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data =",
"while y_index < sample_height: while x_index < basic_width: x =",
"output_directory + \"/figs\" + \"/Sample \" + str(sample_num)) plt.cla() plt.close(fig)",
"-1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) # reshape data into a",
"2-dimensional array contains each group data sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width,",
"+ str(initial_concentration), \"dilution protocol: \" + str(dilution_protocol)]) csv_writer_grouped.writerow(\"\") sample_num =",
"SAMPLE.T sample_num += 1 csv_writer_grouped.writerow([\"Sample \" + str(sample_num)]) for repeat",
"1 y_index += 1 x_index = 0 FULL_RESULT_LIST.append(sample_buffer) FULL_RESULT_LIST =",
"calculate_avg_of_sample, convert_to_percentage from util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as",
"util.calculus import calculate_summary_of_sample, fit_sigmoid_curve import matplotlib.pyplot as plt import numpy",
"of each grid sd_matrix = [] for line in rebuild_24h_data:",
"in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average",
"= read_0h_data() final_sd_data = read_24h_data() # reshape data into the",
"for repeat in SAMPLE: x, y, x_sampling, y_sampling = fit_sigmoid_curve(x_data,",
"control_number_list: number = number - 1 sample = sample_divided_list_24h[number] control_24h_summary",
"- control_0h_average.item()) new_line.append(sd_data) sd_matrix.append(new_line) sd_matrix = np.array(sd_matrix) # split array",
"= np.mean(x_buffer) EC50_AVG_LIST.append(avg) # draw the average curve x_sampling_buffer =",
"[] for line in rebuild_24h_data: new_line = [] for element",
"data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer = [] x_index +=",
"ax.plot(avg, 0.5, 'o', color='black') ax.plot(x_sampling_avg, y_sampling_avg, color='black') plt.savefig(\"./output/\" + output_directory",
"sample_divided_list_0h = split_array_into_samples(rebuild_0h_data, sample_width, sample_height) sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height)",
"< sample_width: data_buffer.append(group[y_index][x]) x += basic_width sample_buffer.append(data_buffer) data_buffer = []",
"sample_num = 0 for SAMPLE in FULL_RESULT_LIST: sample_num += 1",
"for line in x_sampling_buffer: x_sampling_avg.append(np.mean(line)) for line in y_sampling_buffer: y_sampling_avg.append(np.mean(line))",
"sample_divided_list_24h[number] control_24h_summary = control_24h_summary + calculate_summary_of_sample(sample) control_24h_average = control_24h_summary /",
"csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10, EC50_AVG_LIST[sample_num-1]) csv_writer_grouped.writerow([]) csv_writer_grouped.writerow([\"Average EC50\", \"Std\"]) csv_writer_grouped.writerow([average_ec50,",
"draw_single_curve(ax, x, y, x_sampling, y_sampling, optional_color[index]) index += 1 EC50_LIST.append(x_buffer)",
"[] for ec50_index in EC50_LIST[sample_num-1]: ec50_result_list.append(10**ec50_index) csv_writer_grouped.writerow(ec50_result_list) average_ec50 = np.power(10,",
"setting = read_setting_json() setting = setting[\"rule\"] # load experiment parameter",
"+ str(sample_num)]) for repeat in SAMPLE: csv_writer_grouped.writerow(repeat) csv_writer_grouped.writerow(\"\") ec50_result_list =",
"-1)) # reshape data into a 2-dimensional array contains each",
"RESULT_LIST = [] for sample in sd_groups: result = calculate_avg_of_sample(sample,",
"sample_divided_list_24h = split_array_into_samples(rebuild_24h_data, sample_width, sample_height) # handle data of control",
"board rebuild_0h_data = initial_sd_data.reshape((32, -1)) rebuild_24h_data = final_sd_data.reshape((32, -1)) #"
] |
[
"servers that we were able to look up. \"\"\" domains",
"r in records: if r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad()",
"## else: ## # print 'Doing address lookup for', soFar,",
"# print 'Discovered to be', authority, 'for', r ## else:",
"authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg",
"r: Resolver([e[1] for e in r if e[0]])) return DeferredResolver(d)",
"discoverAuthority into several smaller functions documentation \"\"\" from twisted.internet import",
"dns.PORT), # Server to query [dns.Query(host, dns.NS, dns.IN)] # Question",
"self.__dict__ = resolver.__dict__ self.__class__ = resolver.__class__ for d in w:",
"that has references to all the root servers that we",
"Server to query [dns.Query(host, dns.NS, dns.IN)] # Question to ask",
"querying successive authoritative servers to lookup a record, starting from",
"= [r for r in records if r.type == dns.NS]",
"# f = lambda r: (log.msg('Root server address: ' +",
"def placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r, name)(*args, **kw)) return deferred",
"name): if name.startswith('lookup') or name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return",
"+ msg.additional ## addresses = [r for r in records",
"# See LICENSE for details. \"\"\" Resolver implementation for querying",
"lambda r: (log.msg('Root server address: ' + str(r)), r)[1] f",
"the root nameservers. @author: <NAME> todo:: robustify it break discoverAuthority",
"return p.query(timeout=t.pop(0), *args ).addErrback(errback ) return p.query(timeout=t.pop(0), *args ).addErrback(errback )",
"q = dns.Query(name, type, cls) r = client.Resolver(servers=[(auth, dns.PORT)]) d",
"not t: return failure return p.query(timeout=t.pop(0), *args ).addErrback(errback ) return",
"45), # Timeouts p, # Protocol instance (atServer, dns.PORT), #",
"to look up. \"\"\" domains = [chr(ord('a') + i) for",
"Resolver which will eventually become a C{root.Resolver} instance that has",
"i) for i in range(13)] # f = lambda r:",
"list(t) def errback(failure): failure.trap(defer.TimeoutError) if not t: return failure return",
"else: ## # print 'Doing address lookup for', soFar, 'at',",
"def lookupNameservers(host, atServer, p=None): # print 'Nameserver lookup for', host,",
"print '///////', soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p))",
"or name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise",
"def gotRealResolver(self, resolver): w = self.waiting self.__dict__ = resolver.__dict__ self.__class__",
"extractAuthority(msg, cache) if newAuth is not None: # print \"newAuth",
"self.hints ).addCallback(self.discoveredAuthority, name, cls, type, timeout ) return d def",
"return None, nameservers def discoverAuthority(host, roots, cache=None, p=None): if cache",
"part in parts: soFar = part + '.' + soFar",
"\"\"\" Resolver implementation for querying successive authoritative servers to lookup",
"msg.getResult() newAuth, nameservers = extractAuthority(msg, cache) if newAuth is not",
"Protocol instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.A,",
"## yield msg ## msg = msg.getResult() ## records =",
"errback(failure): failure.trap(defer.TimeoutError) if not t: return failure return p.query(timeout=t.pop(0), *args",
"r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r in records:",
"test-case-name: twisted.names.test.test_rootresolve -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories.",
"r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains]",
"class _DummyController: def messageReceived(self, *args): pass class Resolver(common.ResolverBase): def __init__(self,",
"+ '.' + soFar # print '///////', soFar, authority, p",
"Protocol instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.NS,",
"for r in records: if r.type == dns.NS: if str(r.payload.name)",
"in domains] d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e",
"authority, 'for', r ## else: ## # print 'Doing address",
"p.query(timeout=t.pop(0), *args ).addErrback(errback ) return p.query(timeout=t.pop(0), *args ).addErrback(errback ) class",
"soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg",
"= newAuth else: if nameservers: r = str(nameservers[0].payload.name) # print",
"twisted.names import client q = dns.Query(name, type, cls) r =",
"nameservers for addr in records: if addr.type == dns.A and",
"import client q = dns.Query(name, type, cls) r = client.Resolver(servers=[(auth,",
"newAuth, nameservers = extractAuthority(msg, cache) if newAuth is not None:",
"d.callback(resolver) def __getattr__(self, name): if name.startswith('lookup') or name in ('getHostByName',",
"'at', atServer, 'with', p if p is None: p =",
"successive authoritative servers to lookup a record, starting from the",
"self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w = self.waiting",
"it break discoverAuthority into several smaller functions documentation \"\"\" from",
"def __getattr__(self, name): if name.startswith('lookup') or name in ('getHostByName', 'query'):",
"hints def _lookup(self, name, cls, type, timeout): d = discoverAuthority(name,",
"addresses[0].payload.dottedQuad() ## else: ## raise IOError(\"Resolution error\") # print \"Yielding",
"authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg",
"nameservers if not nameservers: return None, nameservers if not records:",
"nameservers. @author: <NAME> todo:: robustify it break discoverAuthority into several",
"not nameservers: return None, nameservers if not records: raise IOError(\"No",
"== dns.A and addr.name == r.name: return addr.payload.dottedQuad(), nameservers return",
"records: if addr.type == dns.A and addr.name == r.name: return",
"# Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE",
"r in records if r.type == dns.NS] # print 'Records",
"(log.msg('Root server address: ' + str(r)), r)[1] f = lambda",
"(atServer, dns.PORT), # Server to query [dns.Query(host, dns.A, dns.IN)] #",
"= self.waiting self.__dict__ = resolver.__dict__ self.__class__ = resolver.__class__ for d",
"def errback(failure): failure.trap(defer.TimeoutError) if not t: return failure return p.query(timeout=t.pop(0),",
"## addresses = [r for r in records if r.type",
"nameservers: return None, nameservers if not records: raise IOError(\"No records\")",
"not records: raise IOError(\"No records\") for r in records: if",
"a record, starting from the root nameservers. @author: <NAME> todo::",
"d).addCallback(f) for d in domains] d = defer.DeferredList(L) d.addCallback(lambda r:",
"name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise AttributeError(name)",
"d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls, type, timeout )",
"msg.authority + msg.additional nameservers = [r for r in records",
"servers to lookup a record, starting from the root nameservers.",
"ask ) def extractAuthority(msg, cache): records = msg.answers + msg.authority",
"defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e in r if e[0]]))",
"t = list(t) def errback(failure): failure.trap(defer.TimeoutError) if not t: return",
"if r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r in",
"('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def bootstrap(resolver):",
"name.startswith('lookup') or name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name)",
"timeout): from twisted.names import client q = dns.Query(name, type, cls)",
"print 'NS for', soFar, ':', nameservers if not nameservers: return",
"'Recursively discovering authority for', r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache,",
"return d def discoveredAuthority(self, auth, name, cls, type, timeout): from",
"nameservers: r = str(nameservers[0].payload.name) # print 'Recursively discovering authority for',",
"== r.name: return addr.payload.dottedQuad(), nameservers return None, nameservers def discoverAuthority(host,",
"## authority = addresses[0].payload.dottedQuad() ## else: ## raise IOError(\"Resolution error\")",
"str(r)), r)[1] f = lambda r: r L = [resolver.getHostByName('%s.root-servers.net'",
"name)(*args, **kw)) return deferred return placeholder class DeferredResolver: def __init__(self,",
"= defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg ## msg =",
"if addr.type == dns.A and addr.name == r.name: return addr.payload.dottedQuad(),",
"in records if r.type == dns.A] ## if addresses: ##",
"[dns.Query(host, dns.A, dns.IN)] # Question to ask ) def extractAuthority(msg,",
"address: ' + str(r)), r)[1] f = lambda r: r",
"= addresses[0].payload.dottedQuad() ## else: ## raise IOError(\"Resolution error\") # print",
"yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def placeholder(*args,",
"roots, cache, p)) yield authority authority = authority.getResult() # print",
"twisted.names import dns from twisted.names import common def retry(t, p,",
"host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar = '' for part",
"ask ) def lookupAddress(host, atServer, p=None): # print 'Address lookup",
") return d def discoveredAuthority(self, auth, name, cls, type, timeout):",
"records = msg.answers + msg.authority + msg.additional ## addresses =",
"common def retry(t, p, *args): assert t, \"Timeout is required\"",
"client q = dns.Query(name, type, cls) r = client.Resolver(servers=[(auth, dns.PORT)])",
"= host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar = '' for",
"list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar =",
"from twisted.internet import defer from twisted.names import dns from twisted.names",
"discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def placeholder(*args, **kw): deferred.addCallback(lambda",
"return None, nameservers if not records: raise IOError(\"No records\") for",
"host, 'at', atServer, 'with', p if p is None: p",
"failure return p.query(timeout=t.pop(0), *args ).addErrback(errback ) return p.query(timeout=t.pop(0), *args ).addErrback(errback",
"# -*- test-case-name: twisted.names.test.test_rootresolve -*- # Copyright (c) 2001-2009 Twisted",
"in records: if addr.type == dns.A and addr.name == r.name:",
"atServer, p=None): # print 'Address lookup for', host, 'at', atServer,",
"d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e in r",
"cls, type, timeout ) return d def discoveredAuthority(self, auth, name,",
"r)[1] f = lambda r: r L = [resolver.getHostByName('%s.root-servers.net' %",
"retry( (1, 3, 11, 45), # Timeouts p, # Protocol",
"cache): records = msg.answers + msg.authority + msg.additional nameservers =",
"IOError(\"No records\") for r in records: if r.type == dns.A:",
"yield msg ## msg = msg.getResult() ## records = msg.answers",
"raise IOError(\"Resolution error\") # print \"Yielding authority\", authority yield authority",
"r: (log.msg('Root server address: ' + str(r)), r)[1] f =",
"to all the root servers that we were able to",
"eventually become a C{root.Resolver} instance that has references to all",
"# print 'Records for', soFar, ':', records # print 'NS",
"def lookupAddress(host, atServer, p=None): # print 'Address lookup for', host,",
"'///////', soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield",
"Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for",
"documentation \"\"\" from twisted.internet import defer from twisted.names import dns",
"for d in domains] d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1]",
"range(13)] # f = lambda r: (log.msg('Root server address: '",
"LICENSE for details. \"\"\" Resolver implementation for querying successive authoritative",
"lookupNameservers(host, atServer, p=None): # print 'Nameserver lookup for', host, 'at',",
"is not None\" authority = newAuth else: if nameservers: r",
"discoverAuthority(host, roots, cache=None, p=None): if cache is None: cache =",
"r.type == dns.NS: if str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers",
"dns.IN)] # Question to ask ) def lookupAddress(host, atServer, p=None):",
"## raise IOError(\"Resolution error\") # print \"Yielding authority\", authority yield",
"in range(13)] # f = lambda r: (log.msg('Root server address:",
"def extractAuthority(msg, cache): records = msg.answers + msg.authority + msg.additional",
"self.hints = hints def _lookup(self, name, cls, type, timeout): d",
"authority, p)) yield msg msg = msg.getResult() newAuth, nameservers =",
"r.payload.dottedQuad() for r in records: if r.type == dns.NS: if",
"import dns from twisted.names import common def retry(t, p, *args):",
"p.query(timeout=t.pop(0), *args ).addErrback(errback ) class _DummyController: def messageReceived(self, *args): pass",
"addr.payload.dottedQuad(), nameservers return None, nameservers def discoverAuthority(host, roots, cache=None, p=None):",
"makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the root nameserver",
"Laboratories. # See LICENSE for details. \"\"\" Resolver implementation for",
"records: if r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r",
"if nameservers: r = str(nameservers[0].payload.name) # print 'Recursively discovering authority",
"= [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains] d =",
"authority = newAuth else: if nameservers: r = str(nameservers[0].payload.name) #",
"error\") # print \"Yielding authority\", authority yield authority discoverAuthority =",
"records if r.type == dns.NS] # print 'Records for', soFar,",
"we were able to look up. \"\"\" domains = [chr(ord('a')",
"= {} rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority",
"print 'Nameserver lookup for', host, 'at', atServer, 'with', p if",
"for', soFar, 'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p))",
"else: if nameservers: r = str(nameservers[0].payload.name) # print 'Recursively discovering",
"type, cls) r = client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q], timeout)",
"d def lookupNameservers(host, atServer, p=None): # print 'Nameserver lookup for',",
"# Protocol instance (atServer, dns.PORT), # Server to query [dns.Query(host,",
"authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority authority =",
"instance that has references to all the root servers that",
"return deferred return placeholder class DeferredResolver: def __init__(self, resolverDeferred): self.waiting",
"if p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False",
"to ask ) def lookupAddress(host, atServer, p=None): # print 'Address",
"raise IOError(\"No records\") for r in records: if r.type ==",
"\"Yielding authority\", authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred,",
"[resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains] d = defer.DeferredList(L)",
"11, 45), # Timeouts p, # Protocol instance (atServer, dns.PORT),",
"starting from the root nameservers. @author: <NAME> todo:: robustify it",
"= r.payload.dottedQuad() for r in records: if r.type == dns.NS:",
"client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d def",
"discoveredAuthority(self, auth, name, cls, type, timeout): from twisted.names import client",
"is None: cache = {} rootAuths = list(roots) parts =",
"for i in range(13)] # f = lambda r: (log.msg('Root",
"[r for r in records if r.type == dns.A] ##",
"which will eventually become a C{root.Resolver} instance that has references",
"== dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r in records: if",
"nameservers if not records: raise IOError(\"No records\") for r in",
"authority = rootAuths.pop() soFar = '' for part in parts:",
"= False return retry( (1, 3, 11, 45), # Timeouts",
"in parts: soFar = part + '.' + soFar #",
"dns.A and addr.name == r.name: return addr.payload.dottedQuad(), nameservers return None,",
"None, nameservers if not records: raise IOError(\"No records\") for r",
"for r in records if r.type == dns.A] ## if",
"dns.Query(name, type, cls) r = client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q],",
"d def discoveredAuthority(self, auth, name, cls, type, timeout): from twisted.names",
"discovering authority for', r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p))",
"print 'Address lookup for', host, 'at', atServer, 'with', p if",
"msg.answers + msg.authority + msg.additional ## addresses = [r for",
"= [chr(ord('a') + i) for i in range(13)] # f",
"## if addresses: ## authority = addresses[0].payload.dottedQuad() ## else: ##",
"'.' + soFar # print '///////', soFar, authority, p msg",
"= msg.getResult() newAuth, nameservers = extractAuthority(msg, cache) if newAuth is",
"msg.additional nameservers = [r for r in records if r.type",
"def discoverAuthority(host, roots, cache=None, p=None): if cache is None: cache",
"w: d.callback(resolver) def __getattr__(self, name): if name.startswith('lookup') or name in",
"= msg.answers + msg.authority + msg.additional ## addresses = [r",
"authority = authority.getResult() # print 'Discovered to be', authority, 'for',",
"soFar = '' for part in parts: soFar = part",
"def bootstrap(resolver): \"\"\"Lookup the root nameserver addresses using the given",
"authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def",
"# print '///////', soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar, authority,",
"def makePlaceholder(deferred, name): def placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r, name)(*args,",
"(atServer, dns.PORT), # Server to query [dns.Query(host, dns.NS, dns.IN)] #",
"= rootAuths.pop() soFar = '' for part in parts: soFar",
"twisted.internet import defer from twisted.names import dns from twisted.names import",
"if r.type == dns.A] ## if addresses: ## authority =",
"records if r.type == dns.A] ## if addresses: ## authority",
"class Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self) self.hints = hints def",
").addCallback(self.discoveredAuthority, name, cls, type, timeout ) return d def discoveredAuthority(self,",
"cache) if newAuth is not None: # print \"newAuth is",
"return p.query(timeout=t.pop(0), *args ).addErrback(errback ) class _DummyController: def messageReceived(self, *args):",
"d.addCallback(r.filterAnswers) return d def lookupNameservers(host, atServer, p=None): # print 'Nameserver",
"authority.getResult() # print 'Discovered to be', authority, 'for', r ##",
"parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar = ''",
"r.type == dns.NS] # print 'Records for', soFar, ':', records",
"else: ## raise IOError(\"Resolution error\") # print \"Yielding authority\", authority",
"[dns.Query(host, dns.NS, dns.IN)] # Question to ask ) def lookupAddress(host,",
"if cache is None: cache = {} rootAuths = list(roots)",
"records # print 'NS for', soFar, ':', nameservers if not",
"_lookup(self, name, cls, type, timeout): d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority,",
"domains] d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e in",
"name) raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the root nameserver addresses",
"given resolver Return a Resolver which will eventually become a",
"' + str(r)), r)[1] f = lambda r: r L",
"'Doing address lookup for', soFar, 'at', authority ## msg =",
"return failure return p.query(timeout=t.pop(0), *args ).addErrback(errback ) return p.query(timeout=t.pop(0), *args",
"to query [dns.Query(host, dns.NS, dns.IN)] # Question to ask )",
"## msg = msg.getResult() ## records = msg.answers + msg.authority",
"deferred.addCallback(lambda r: getattr(r, name)(*args, **kw)) return deferred return placeholder class",
"3, 11, 45), # Timeouts p, # Protocol instance (atServer,",
"Resolver implementation for querying successive authoritative servers to lookup a",
"authority authority = authority.getResult() # print 'Discovered to be', authority,",
"\"\"\" from twisted.internet import defer from twisted.names import dns from",
"= hints def _lookup(self, name, cls, type, timeout): d =",
"# print 'Address lookup for', host, 'at', atServer, 'with', p",
"return retry( (1, 3, 11, 45), # Timeouts p, #",
"## # print 'Doing address lookup for', soFar, 'at', authority",
"Question to ask ) def lookupAddress(host, atServer, p=None): # print",
"into several smaller functions documentation \"\"\" from twisted.internet import defer",
"+ msg.authority + msg.additional ## addresses = [r for r",
"*args): assert t, \"Timeout is required\" t = list(t) def",
"todo:: robustify it break discoverAuthority into several smaller functions documentation",
"# Server to query [dns.Query(host, dns.A, dns.IN)] # Question to",
"== dns.NS: if str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers for",
"= '' for part in parts: soFar = part +",
"auth, name, cls, type, timeout): from twisted.names import client q",
"lookup a record, starting from the root nameservers. @author: <NAME>",
"= lambda r: r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for",
"type, timeout): from twisted.names import client q = dns.Query(name, type,",
"soFar, ':', nameservers if not nameservers: return None, nameservers if",
"None\" authority = newAuth else: if nameservers: r = str(nameservers[0].payload.name)",
"p, # Protocol instance (atServer, dns.PORT), # Server to query",
"name, cls, type, timeout): from twisted.names import client q =",
"f = lambda r: (log.msg('Root server address: ' + str(r)),",
"cache[str(r.name)] = r.payload.dottedQuad() for r in records: if r.type ==",
"resolver.__dict__ self.__class__ = resolver.__class__ for d in w: d.callback(resolver) def",
"r = str(nameservers[0].payload.name) # print 'Recursively discovering authority for', r",
"lookup for', host, 'at', atServer, 'with', p if p is",
"-*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. # See",
"Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self) self.hints = hints def _lookup(self,",
"p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1, 3,",
"retry(t, p, *args): assert t, \"Timeout is required\" t =",
"soFar = part + '.' + soFar # print '///////',",
"authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def placeholder(*args, **kw):",
"import common def retry(t, p, *args): assert t, \"Timeout is",
"'Records for', soFar, ':', records # print 'NS for', soFar,",
"if newAuth is not None: # print \"newAuth is not",
"dns.PORT), # Server to query [dns.Query(host, dns.A, dns.IN)] # Question",
"resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w = self.waiting self.__dict__ = resolver.__dict__",
"were able to look up. \"\"\" domains = [chr(ord('a') +",
"up. \"\"\" domains = [chr(ord('a') + i) for i in",
"C{root.Resolver} instance that has references to all the root servers",
"'with', p if p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy",
"lookup for', soFar, 'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority,",
"record, starting from the root nameservers. @author: <NAME> todo:: robustify",
"twisted.names import common def retry(t, p, *args): assert t, \"Timeout",
"## records = msg.answers + msg.authority + msg.additional ## addresses",
"dns.IN)] # Question to ask ) def extractAuthority(msg, cache): records",
"addr in records: if addr.type == dns.A and addr.name ==",
"to lookup a record, starting from the root nameservers. @author:",
"if not t: return failure return p.query(timeout=t.pop(0), *args ).addErrback(errback )",
"p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return",
"details. \"\"\" Resolver implementation for querying successive authoritative servers to",
"able to look up. \"\"\" domains = [chr(ord('a') + i)",
"[chr(ord('a') + i) for i in range(13)] # f =",
"from twisted.names import common def retry(t, p, *args): assert t,",
"= msg.getResult() ## records = msg.answers + msg.authority + msg.additional",
"has references to all the root servers that we were",
"instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.NS, dns.IN)]",
"several smaller functions documentation \"\"\" from twisted.internet import defer from",
").addErrback(errback ) return p.query(timeout=t.pop(0), *args ).addErrback(errback ) class _DummyController: def",
"defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg = msg.getResult() newAuth, nameservers",
"**kw)) return deferred return placeholder class DeferredResolver: def __init__(self, resolverDeferred):",
"msg.getResult() ## records = msg.answers + msg.authority + msg.additional ##",
"*args): pass class Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self) self.hints =",
"## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg ##",
"assert t, \"Timeout is required\" t = list(t) def errback(failure):",
"msg msg = msg.getResult() newAuth, nameservers = extractAuthority(msg, cache) if",
"+ msg.authority + msg.additional nameservers = [r for r in",
"= [r for r in records if r.type == dns.A]",
"dns from twisted.names import common def retry(t, p, *args): assert",
"is not None: # print \"newAuth is not None\" authority",
"references to all the root servers that we were able",
"t, \"Timeout is required\" t = list(t) def errback(failure): failure.trap(defer.TimeoutError)",
"parts.reverse() authority = rootAuths.pop() soFar = '' for part in",
"records: raise IOError(\"No records\") for r in records: if r.type",
"dns.NS, dns.IN)] # Question to ask ) def lookupAddress(host, atServer,",
"failure.trap(defer.TimeoutError) if not t: return failure return p.query(timeout=t.pop(0), *args ).addErrback(errback",
"= part + '.' + soFar # print '///////', soFar,",
"d.addCallback(lambda r: Resolver([e[1] for e in r if e[0]])) return",
"= r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d def lookupNameservers(host, atServer, p=None):",
"self.waiting self.__dict__ = resolver.__dict__ self.__class__ = resolver.__class__ for d in",
"cache=None, p=None): if cache is None: cache = {} rootAuths",
") return p.query(timeout=t.pop(0), *args ).addErrback(errback ) class _DummyController: def messageReceived(self,",
"== dns.A] ## if addresses: ## authority = addresses[0].payload.dottedQuad() ##",
"p=None): # print 'Address lookup for', host, 'at', atServer, 'with',",
"in records if r.type == dns.NS] # print 'Records for',",
"in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def",
"type, timeout ) return d def discoveredAuthority(self, auth, name, cls,",
"for r in records: if r.type == dns.A: cache[str(r.name)] =",
"cls) r = client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers)",
"\"\"\" domains = [chr(ord('a') + i) for i in range(13)]",
"is required\" t = list(t) def errback(failure): failure.trap(defer.TimeoutError) if not",
"robustify it break discoverAuthority into several smaller functions documentation \"\"\"",
"timeout ) return d def discoveredAuthority(self, auth, name, cls, type,",
"print 'Records for', soFar, ':', records # print 'NS for',",
"cache = {} rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse()",
"None: # print \"newAuth is not None\" authority = newAuth",
"smaller functions documentation \"\"\" from twisted.internet import defer from twisted.names",
"r in records if r.type == dns.A] ## if addresses:",
"See LICENSE for details. \"\"\" Resolver implementation for querying successive",
"msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg ## msg",
"**kw): deferred.addCallback(lambda r: getattr(r, name)(*args, **kw)) return deferred return placeholder",
"to ask ) def extractAuthority(msg, cache): records = msg.answers +",
"None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1,",
"return addr.payload.dottedQuad(), nameservers return None, nameservers def discoverAuthority(host, roots, cache=None,",
"for', soFar, ':', nameservers if not nameservers: return None, nameservers",
"cache is None: cache = {} rootAuths = list(roots) parts",
"return placeholder class DeferredResolver: def __init__(self, resolverDeferred): self.waiting = []",
"implementation for querying successive authoritative servers to lookup a record,",
"yield msg msg = msg.getResult() newAuth, nameservers = extractAuthority(msg, cache)",
"msg = msg.getResult() ## records = msg.answers + msg.authority +",
"f = lambda r: r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f)",
"'' for part in parts: soFar = part + '.'",
"be', authority, 'for', r ## else: ## # print 'Doing",
"print 'Doing address lookup for', soFar, 'at', authority ## msg",
"if str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers for addr in",
"dns.NS] # print 'Records for', soFar, ':', records # print",
"defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r,",
"Question to ask ) def extractAuthority(msg, cache): records = msg.answers",
"msg ## msg = msg.getResult() ## records = msg.answers +",
"for d in w: d.callback(resolver) def __getattr__(self, name): if name.startswith('lookup')",
"print \"Yielding authority\", authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def",
"'NS for', soFar, ':', nameservers if not nameservers: return None,",
"parts: soFar = part + '.' + soFar # print",
"to be', authority, 'for', r ## else: ## # print",
"timeout) d.addCallback(r.filterAnswers) return d def lookupNameservers(host, atServer, p=None): # print",
"*args ).addErrback(errback ) return p.query(timeout=t.pop(0), *args ).addErrback(errback ) class _DummyController:",
"+ msg.additional nameservers = [r for r in records if",
"dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1, 3, 11, 45),",
"look up. \"\"\" domains = [chr(ord('a') + i) for i",
"for part in parts: soFar = part + '.' +",
"from the root nameservers. @author: <NAME> todo:: robustify it break",
"{} rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority =",
"r.type == dns.A] ## if addresses: ## authority = addresses[0].payload.dottedQuad()",
"= defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority authority = authority.getResult()",
"DeferredResolver: def __init__(self, resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self,",
"# Question to ask ) def lookupAddress(host, atServer, p=None): #",
"name, cls, type, timeout): d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name,",
"# Timeouts p, # Protocol instance (atServer, dns.PORT), # Server",
"p if p is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy =",
"nameservers = [r for r in records if r.type ==",
"addr.name == r.name: return addr.payload.dottedQuad(), nameservers return None, nameservers def",
"for r in records if r.type == dns.NS] # print",
"to query [dns.Query(host, dns.A, dns.IN)] # Question to ask )",
"= defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg = msg.getResult() newAuth,",
"= resolver.__class__ for d in w: d.callback(resolver) def __getattr__(self, name):",
"<NAME> todo:: robustify it break discoverAuthority into several smaller functions",
"a Resolver which will eventually become a C{root.Resolver} instance that",
"for', soFar, ':', records # print 'NS for', soFar, ':',",
"= resolver.__dict__ self.__class__ = resolver.__class__ for d in w: d.callback(resolver)",
"raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the root nameserver addresses using",
"'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup",
") def extractAuthority(msg, cache): records = msg.answers + msg.authority +",
"become a C{root.Resolver} instance that has references to all the",
"bootstrap(resolver): \"\"\"Lookup the root nameserver addresses using the given resolver",
"records: if r.type == dns.NS: if str(r.payload.name) in cache: return",
"'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield",
"# print 'Nameserver lookup for', host, 'at', atServer, 'with', p",
"extractAuthority(msg, cache): records = msg.answers + msg.authority + msg.additional nameservers",
"if not records: raise IOError(\"No records\") for r in records:",
"class DeferredResolver: def __init__(self, resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def",
"= list(t) def errback(failure): failure.trap(defer.TimeoutError) if not t: return failure",
"= defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name): def placeholder(*args, **kw): deferred.addCallback(lambda r:",
"dns.A, dns.IN)] # Question to ask ) def extractAuthority(msg, cache):",
"= authority.getResult() # print 'Discovered to be', authority, 'for', r",
"'Discovered to be', authority, 'for', r ## else: ## #",
"[r for r in records if r.type == dns.NS] #",
"-*- test-case-name: twisted.names.test.test_rootresolve -*- # Copyright (c) 2001-2009 Twisted Matrix",
"hints): common.ResolverBase.__init__(self) self.hints = hints def _lookup(self, name, cls, type,",
"return d def lookupNameservers(host, atServer, p=None): # print 'Nameserver lookup",
"None, nameservers def discoverAuthority(host, roots, cache=None, p=None): if cache is",
"the given resolver Return a Resolver which will eventually become",
"@author: <NAME> todo:: robustify it break discoverAuthority into several smaller",
"atServer, p=None): # print 'Nameserver lookup for', host, 'at', atServer,",
"nameservers def discoverAuthority(host, roots, cache=None, p=None): if cache is None:",
"addresses: ## authority = addresses[0].payload.dottedQuad() ## else: ## raise IOError(\"Resolution",
"twisted.names.test.test_rootresolve -*- # Copyright (c) 2001-2009 Twisted Matrix Laboratories. #",
"common.ResolverBase.__init__(self) self.hints = hints def _lookup(self, name, cls, type, timeout):",
"authority = addresses[0].payload.dottedQuad() ## else: ## raise IOError(\"Resolution error\") #",
"timeout): d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls, type, timeout",
"r in records: if r.type == dns.NS: if str(r.payload.name) in",
"the root servers that we were able to look up.",
"AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the root nameserver addresses using the",
").addErrback(errback ) class _DummyController: def messageReceived(self, *args): pass class Resolver(common.ResolverBase):",
"def __init__(self, hints): common.ResolverBase.__init__(self) self.hints = hints def _lookup(self, name,",
"= extractAuthority(msg, cache) if newAuth is not None: # print",
"msg.additional ## addresses = [r for r in records if",
"d in w: d.callback(resolver) def __getattr__(self, name): if name.startswith('lookup') or",
"# Question to ask ) def extractAuthority(msg, cache): records =",
"nameserver addresses using the given resolver Return a Resolver which",
"address lookup for', soFar, 'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar,",
") def lookupAddress(host, atServer, p=None): # print 'Address lookup for',",
"\"newAuth is not None\" authority = newAuth else: if nameservers:",
"if r.type == dns.NS] # print 'Records for', soFar, ':',",
"rootAuths = list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop()",
"IOError(\"Resolution error\") # print \"Yielding authority\", authority yield authority discoverAuthority",
"cache[str(r.payload.name)], nameservers for addr in records: if addr.type == dns.A",
"dns.NS: if str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers for addr",
"+ str(r)), r)[1] f = lambda r: r L =",
"authority for', r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield",
"deferred return placeholder class DeferredResolver: def __init__(self, resolverDeferred): self.waiting =",
"def __init__(self, resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver):",
"yield authority authority = authority.getResult() # print 'Discovered to be',",
"# print \"Yielding authority\", authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority)",
"for', r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority",
"# print \"newAuth is not None\" authority = newAuth else:",
"name): def placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r, name)(*args, **kw)) return",
"d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d def lookupNameservers(host, atServer,",
"placeholder class DeferredResolver: def __init__(self, resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver)",
"addresses using the given resolver Return a Resolver which will",
"server address: ' + str(r)), r)[1] f = lambda r:",
"in records: if r.type == dns.A: cache[str(r.name)] = r.payload.dottedQuad() for",
"p)) yield authority authority = authority.getResult() # print 'Discovered to",
") class _DummyController: def messageReceived(self, *args): pass class Resolver(common.ResolverBase): def",
"r ## else: ## # print 'Doing address lookup for',",
"resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w =",
"i in range(13)] # f = lambda r: (log.msg('Root server",
"in cache: return cache[str(r.payload.name)], nameservers for addr in records: if",
"makePlaceholder(deferred, name): def placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r, name)(*args, **kw))",
"_DummyController: def messageReceived(self, *args): pass class Resolver(common.ResolverBase): def __init__(self, hints):",
"dns.A] ## if addresses: ## authority = addresses[0].payload.dottedQuad() ## else:",
"records = msg.answers + msg.authority + msg.additional nameservers = [r",
"break discoverAuthority into several smaller functions documentation \"\"\" from twisted.internet",
"% d).addCallback(f) for d in domains] d = defer.DeferredList(L) d.addCallback(lambda",
"__getattr__(self, name): if name.startswith('lookup') or name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred())",
"is None: p = dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry(",
"None: cache = {} rootAuths = list(roots) parts = host.rstrip('.').split('.')",
"str(nameservers[0].payload.name) # print 'Recursively discovering authority for', r authority =",
"for addr in records: if addr.type == dns.A and addr.name",
"print 'Recursively discovering authority for', r authority = defer.waitForDeferred(discoverAuthority(r, roots,",
"if name.startswith('lookup') or name in ('getHostByName', 'query'): self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1],",
"all the root servers that we were able to look",
"msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg = msg.getResult()",
"str(r.payload.name) in cache: return cache[str(r.payload.name)], nameservers for addr in records:",
"(1, 3, 11, 45), # Timeouts p, # Protocol instance",
"p)) ## yield msg ## msg = msg.getResult() ## records",
"if r.type == dns.NS: if str(r.payload.name) in cache: return cache[str(r.payload.name)],",
"addresses = [r for r in records if r.type ==",
"will eventually become a C{root.Resolver} instance that has references to",
"'Address lookup for', host, 'at', atServer, 'with', p if p",
"soFar # print '///////', soFar, authority, p msg = defer.waitForDeferred(lookupNameservers(soFar,",
"r: getattr(r, name)(*args, **kw)) return deferred return placeholder class DeferredResolver:",
"domains = [chr(ord('a') + i) for i in range(13)] #",
"for details. \"\"\" Resolver implementation for querying successive authoritative servers",
"r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d def lookupNameservers(host, atServer, p=None): #",
"import defer from twisted.names import dns from twisted.names import common",
"2001-2009 Twisted Matrix Laboratories. # See LICENSE for details. \"\"\"",
"return cache[str(r.payload.name)], nameservers for addr in records: if addr.type ==",
"msg.authority + msg.additional ## addresses = [r for r in",
"from twisted.names import dns from twisted.names import common def retry(t,",
"t: return failure return p.query(timeout=t.pop(0), *args ).addErrback(errback ) return p.query(timeout=t.pop(0),",
"# print 'Doing address lookup for', soFar, 'at', authority ##",
"atServer, 'with', p if p is None: p = dns.DNSDatagramProtocol(_DummyController())",
"Return a Resolver which will eventually become a C{root.Resolver} instance",
"return makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the root",
"= dns.DNSDatagramProtocol(_DummyController()) p.noisy = False return retry( (1, 3, 11,",
"dns.PORT)]) d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d def lookupNameservers(host,",
"dns.A: cache[str(r.name)] = r.payload.dottedQuad() for r in records: if r.type",
"= msg.answers + msg.authority + msg.additional nameservers = [r for",
"= str(nameservers[0].payload.name) # print 'Recursively discovering authority for', r authority",
"placeholder(*args, **kw): deferred.addCallback(lambda r: getattr(r, name)(*args, **kw)) return deferred return",
"soFar, ':', records # print 'NS for', soFar, ':', nameservers",
"name, cls, type, timeout ) return d def discoveredAuthority(self, auth,",
"roots, cache=None, p=None): if cache is None: cache = {}",
"__init__(self, hints): common.ResolverBase.__init__(self) self.hints = hints def _lookup(self, name, cls,",
"getattr(r, name)(*args, **kw)) return deferred return placeholder class DeferredResolver: def",
"= [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w = self.waiting self.__dict__",
"and addr.name == r.name: return addr.payload.dottedQuad(), nameservers return None, nameservers",
"in records: if r.type == dns.NS: if str(r.payload.name) in cache:",
"authority\", authority yield authority discoverAuthority = defer.deferredGenerator(discoverAuthority) def makePlaceholder(deferred, name):",
"False return retry( (1, 3, 11, 45), # Timeouts p,",
"w = self.waiting self.__dict__ = resolver.__dict__ self.__class__ = resolver.__class__ for",
"def messageReceived(self, *args): pass class Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self)",
"authoritative servers to lookup a record, starting from the root",
"= client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return d",
"in w: d.callback(resolver) def __getattr__(self, name): if name.startswith('lookup') or name",
"# Server to query [dns.Query(host, dns.NS, dns.IN)] # Question to",
"newAuth else: if nameservers: r = str(nameservers[0].payload.name) # print 'Recursively",
"newAuth is not None: # print \"newAuth is not None\"",
"root servers that we were able to look up. \"\"\"",
"= list(roots) parts = host.rstrip('.').split('.') parts.reverse() authority = rootAuths.pop() soFar",
"p=None): if cache is None: cache = {} rootAuths =",
"cache, p)) yield authority authority = authority.getResult() # print 'Discovered",
"p)) yield msg msg = msg.getResult() newAuth, nameservers = extractAuthority(msg,",
"= lambda r: (log.msg('Root server address: ' + str(r)), r)[1]",
"functions documentation \"\"\" from twisted.internet import defer from twisted.names import",
"= dns.Query(name, type, cls) r = client.Resolver(servers=[(auth, dns.PORT)]) d =",
"nameservers return None, nameservers def discoverAuthority(host, roots, cache=None, p=None): if",
"Server to query [dns.Query(host, dns.A, dns.IN)] # Question to ask",
"discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls, type, timeout ) return d",
"a C{root.Resolver} instance that has references to all the root",
"p msg = defer.waitForDeferred(lookupNameservers(soFar, authority, p)) yield msg msg =",
"type, timeout): d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls, type,",
"r authority = defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority authority",
"+ i) for i in range(13)] # f = lambda",
"resolver): w = self.waiting self.__dict__ = resolver.__dict__ self.__class__ = resolver.__class__",
"L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in domains] d",
"nameservers = extractAuthority(msg, cache) if newAuth is not None: #",
"self.__class__ = resolver.__class__ for d in w: d.callback(resolver) def __getattr__(self,",
"def discoveredAuthority(self, auth, name, cls, type, timeout): from twisted.names import",
"lookupAddress(host, atServer, p=None): # print 'Address lookup for', host, 'at',",
"not None: # print \"newAuth is not None\" authority =",
"def _lookup(self, name, cls, type, timeout): d = discoverAuthority(name, self.hints",
"'Nameserver lookup for', host, 'at', atServer, 'with', p if p",
"addr.type == dns.A and addr.name == r.name: return addr.payload.dottedQuad(), nameservers",
"= discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls, type, timeout ) return",
"if addresses: ## authority = addresses[0].payload.dottedQuad() ## else: ## raise",
"r = client.Resolver(servers=[(auth, dns.PORT)]) d = r.queryUDP([q], timeout) d.addCallback(r.filterAnswers) return",
"Timeouts p, # Protocol instance (atServer, dns.PORT), # Server to",
"if not nameservers: return None, nameservers if not records: raise",
"+ soFar # print '///////', soFar, authority, p msg =",
"not None\" authority = newAuth else: if nameservers: r =",
"## else: ## raise IOError(\"Resolution error\") # print \"Yielding authority\",",
"d in domains] d = defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for",
"Matrix Laboratories. # See LICENSE for details. \"\"\" Resolver implementation",
"def retry(t, p, *args): assert t, \"Timeout is required\" t",
"query [dns.Query(host, dns.NS, dns.IN)] # Question to ask ) def",
"instance (atServer, dns.PORT), # Server to query [dns.Query(host, dns.A, dns.IN)]",
"root nameservers. @author: <NAME> todo:: robustify it break discoverAuthority into",
"== dns.NS] # print 'Records for', soFar, ':', records #",
"= defer.DeferredList(L) d.addCallback(lambda r: Resolver([e[1] for e in r if",
"[] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w = self.waiting self.__dict__ =",
"defer.waitForDeferred(discoverAuthority(r, roots, cache, p)) yield authority authority = authority.getResult() #",
"p=None): # print 'Nameserver lookup for', host, 'at', atServer, 'with',",
"r: r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d in",
"query [dns.Query(host, dns.A, dns.IN)] # Question to ask ) def",
"resolver.__class__ for d in w: d.callback(resolver) def __getattr__(self, name): if",
"':', nameservers if not nameservers: return None, nameservers if not",
"resolver Return a Resolver which will eventually become a C{root.Resolver}",
"lambda r: r L = [resolver.getHostByName('%s.root-servers.net' % d).addCallback(f) for d",
"# print 'NS for', soFar, ':', nameservers if not nameservers:",
"p, *args): assert t, \"Timeout is required\" t = list(t)",
"Twisted Matrix Laboratories. # See LICENSE for details. \"\"\" Resolver",
"msg = msg.getResult() newAuth, nameservers = extractAuthority(msg, cache) if newAuth",
"rootAuths.pop() soFar = '' for part in parts: soFar =",
"print 'Discovered to be', authority, 'for', r ## else: ##",
"(c) 2001-2009 Twisted Matrix Laboratories. # See LICENSE for details.",
"the root nameserver addresses using the given resolver Return a",
"part + '.' + soFar # print '///////', soFar, authority,",
"self.waiting.append(defer.Deferred()) return makePlaceholder(self.waiting[-1], name) raise AttributeError(name) def bootstrap(resolver): \"\"\"Lookup the",
"'for', r ## else: ## # print 'Doing address lookup",
"authority, p)) ## yield msg ## msg = msg.getResult() ##",
"r.name: return addr.payload.dottedQuad(), nameservers return None, nameservers def discoverAuthority(host, roots,",
"from twisted.names import client q = dns.Query(name, type, cls) r",
"root nameserver addresses using the given resolver Return a Resolver",
"required\" t = list(t) def errback(failure): failure.trap(defer.TimeoutError) if not t:",
"cls, type, timeout): d = discoverAuthority(name, self.hints ).addCallback(self.discoveredAuthority, name, cls,",
"for querying successive authoritative servers to lookup a record, starting",
"# print 'Recursively discovering authority for', r authority = defer.waitForDeferred(discoverAuthority(r,",
"defer.waitForDeferred(lookupAddress(soFar, authority, p)) ## yield msg ## msg = msg.getResult()",
"cache: return cache[str(r.payload.name)], nameservers for addr in records: if addr.type",
"\"\"\"Lookup the root nameserver addresses using the given resolver Return",
"cls, type, timeout): from twisted.names import client q = dns.Query(name,",
"print \"newAuth is not None\" authority = newAuth else: if",
"\"Timeout is required\" t = list(t) def errback(failure): failure.trap(defer.TimeoutError) if",
"for', host, 'at', atServer, 'with', p if p is None:",
"__init__(self, resolverDeferred): self.waiting = [] resolverDeferred.addCallback(self.gotRealResolver) def gotRealResolver(self, resolver): w",
"':', records # print 'NS for', soFar, ':', nameservers if",
"soFar, 'at', authority ## msg = defer.waitForDeferred(lookupAddress(soFar, authority, p)) ##",
"gotRealResolver(self, resolver): w = self.waiting self.__dict__ = resolver.__dict__ self.__class__ =",
"p.noisy = False return retry( (1, 3, 11, 45), #",
"msg.answers + msg.authority + msg.additional nameservers = [r for r",
"*args ).addErrback(errback ) class _DummyController: def messageReceived(self, *args): pass class",
"using the given resolver Return a Resolver which will eventually",
"messageReceived(self, *args): pass class Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self) self.hints",
"defer from twisted.names import dns from twisted.names import common def",
"that we were able to look up. \"\"\" domains =",
"pass class Resolver(common.ResolverBase): def __init__(self, hints): common.ResolverBase.__init__(self) self.hints = hints",
"records\") for r in records: if r.type == dns.A: cache[str(r.name)]"
] |
[
"as np from PIL import Image from absl import app",
"# ================================================================ # MIT License # Copyright (c) 2021 edwardyehuang",
"import flags from common_flags import FLAGS from ids.voc2012 import get_colormap",
"get_colormap as get_voc2012_colormap from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\",",
"absl import app from absl import flags from common_flags import",
"os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename) output_path",
"================================================================ import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1,",
"img.save(output_path, format=\"PNG\") counter += 1 tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name",
"def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap = colormap.astype(np.uint8) counter = 0",
"\"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap = colormap.astype(np.uint8) counter",
"import Image from absl import app from absl import flags",
"img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter += 1 tf.print(\"Processed",
"\"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None,",
"output_dir=None, colormap=None): colormap = colormap.astype(np.uint8) counter = 0 if not",
"= {colormap_name}\") if FLAGS.ignore_label == 0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir,",
"edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__),",
"License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import",
"get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir path\") flags.DEFINE_string(\"output_dir\", None,",
"os.path.exists(output_dir): os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename)",
"\"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None):",
"sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow",
"# Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os,",
"Image.open(input_path) if img.mode != \"L\" and img.mode != \"P\": continue",
"get_voc2012_colormap from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input",
"def main(argv): colormap_name = FLAGS.colormap colormap_name = colormap_name.lower() if colormap_name",
"main(argv): colormap_name = FLAGS.colormap colormap_name = colormap_name.lower() if colormap_name ==",
"ValueError(f\"Not support colormap = {colormap_name}\") if FLAGS.ignore_label == 0: colormap",
"{colormap_name}\") if FLAGS.ignore_label == 0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir,",
"raise ValueError(f\"Not support colormap = {colormap_name}\") if FLAGS.ignore_label == 0:",
"img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter += 1 tf.print(\"Processed {}\".format(counter)) def",
"from ids.voc2012 import get_colormap as get_voc2012_colormap from ids.cityscapes_fine import get_colormap",
"filename) img = Image.open(input_path) if img.mode != \"L\" and img.mode",
"get_voc2012_colormap() elif colormap_name == \"cityscapes\": colormap = get_cityscapes_colormap() else: raise",
"colormap = colormap.astype(np.uint8) counter = 0 if not os.path.exists(output_dir): os.mkdir(output_dir)",
"app from absl import flags from common_flags import FLAGS from",
"colormap.astype(np.uint8) counter = 0 if not os.path.exists(output_dir): os.mkdir(output_dir) for filename",
"colormap_name.lower() if colormap_name == \"voc2012\": colormap = get_voc2012_colormap() elif colormap_name",
"np from PIL import Image from absl import app from",
"colormap = get_voc2012_colormap() elif colormap_name == \"cityscapes\": colormap = get_cityscapes_colormap()",
"os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow as tf import numpy",
"os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import",
"{}\".format(counter)) def main(argv): colormap_name = FLAGS.colormap colormap_name = colormap_name.lower() if",
"tf import numpy as np from PIL import Image from",
"if colormap_name == \"voc2012\": colormap = get_voc2012_colormap() elif colormap_name ==",
"if FLAGS.ignore_label == 0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap)",
"from absl import flags from common_flags import FLAGS from ids.voc2012",
"flags.DEFINE_string(\"input_dir\", None, \"input dir path\") flags.DEFINE_string(\"output_dir\", None, \"output dir path\")",
"rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow as",
"\"input dir path\") flags.DEFINE_string(\"output_dir\", None, \"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\",",
"= os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow as tf",
"!= \"P\": continue img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter",
"format=\"PNG\") counter += 1 tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name =",
"img = Image.open(input_path) if img.mode != \"L\" and img.mode !=",
"path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def",
"2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os, sys rootpath =",
"colormap_name == \"voc2012\": colormap = get_voc2012_colormap() elif colormap_name == \"cityscapes\":",
"= img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter += 1 tf.print(\"Processed {}\".format(counter))",
"1 tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name = FLAGS.colormap colormap_name =",
"filename in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir,",
"import get_colormap as get_voc2012_colormap from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap",
"= 0 if not os.path.exists(output_dir): os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir):",
"FLAGS from ids.voc2012 import get_colormap as get_voc2012_colormap from ids.cityscapes_fine import",
"tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename) img",
"(c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os, sys rootpath",
"sys.path.insert(1, rootpath) import tensorflow as tf import numpy as np",
"colormap = {colormap_name}\") if FLAGS.ignore_label == 0: colormap = colormap[1:]",
"ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir path\")",
"input_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename) img =",
"import app from absl import flags from common_flags import FLAGS",
"colormap=None): colormap = colormap.astype(np.uint8) counter = 0 if not os.path.exists(output_dir):",
"else: raise ValueError(f\"Not support colormap = {colormap_name}\") if FLAGS.ignore_label ==",
"for filename in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename) output_path =",
"if not os.path.exists(output_dir): os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir): input_path =",
"# MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) #",
"!= \"L\" and img.mode != \"P\": continue img = img.convert(\"P\")",
"= get_cityscapes_colormap() else: raise ValueError(f\"Not support colormap = {colormap_name}\") if",
"support colormap = {colormap_name}\") if FLAGS.ignore_label == 0: colormap =",
"# ================================================================ import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir))",
"tensorflow as tf import numpy as np from PIL import",
"colormap_name == \"cityscapes\": colormap = get_cityscapes_colormap() else: raise ValueError(f\"Not support",
"label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap = colormap.astype(np.uint8) counter =",
"colormap_name = colormap_name.lower() if colormap_name == \"voc2012\": colormap = get_voc2012_colormap()",
"FLAGS.colormap colormap_name = colormap_name.lower() if colormap_name == \"voc2012\": colormap =",
"not os.path.exists(output_dir): os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir,",
"flags.DEFINE_string(\"output_dir\", None, \"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\",",
"colormap_name = FLAGS.colormap colormap_name = colormap_name.lower() if colormap_name == \"voc2012\":",
"counter = 0 if not os.path.exists(output_dir): os.mkdir(output_dir) for filename in",
"continue img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter += 1",
"img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter += 1 tf.print(\"Processed {}\".format(counter)) def main(argv):",
"common_flags import FLAGS from ids.voc2012 import get_colormap as get_voc2012_colormap from",
"counter += 1 tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name = FLAGS.colormap",
"os.pardir)) sys.path.insert(1, rootpath) import tensorflow as tf import numpy as",
"flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def apply_colormap_to_dir(input_dir,",
"\"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore",
"PIL import Image from absl import app from absl import",
"absl import flags from common_flags import FLAGS from ids.voc2012 import",
"dir path\") flags.DEFINE_string(\"output_dir\", None, \"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap",
"os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath) import tensorflow as tf import",
"img.mode != \"L\" and img.mode != \"P\": continue img =",
"import numpy as np from PIL import Image from absl",
"= colormap_name.lower() if colormap_name == \"voc2012\": colormap = get_voc2012_colormap() elif",
"as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir path\") flags.DEFINE_string(\"output_dir\", None, \"output",
"as tf import numpy as np from PIL import Image",
"colormap = get_cityscapes_colormap() else: raise ValueError(f\"Not support colormap = {colormap_name}\")",
"as get_voc2012_colormap from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None,",
"in tf.io.gfile.listdir(input_dir): input_path = os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename)",
"= os.path.join(output_dir, filename) img = Image.open(input_path) if img.mode != \"L\"",
"FLAGS.ignore_label == 0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap) if",
"255, \"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap = colormap.astype(np.uint8)",
"+= 1 tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name = FLAGS.colormap colormap_name",
"0 if not os.path.exists(output_dir): os.mkdir(output_dir) for filename in tf.io.gfile.listdir(input_dir): input_path",
"= get_voc2012_colormap() elif colormap_name == \"cityscapes\": colormap = get_cityscapes_colormap() else:",
"import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir path\") flags.DEFINE_string(\"output_dir\",",
"= Image.open(input_path) if img.mode != \"L\" and img.mode != \"P\":",
"os.path.join(output_dir, filename) img = Image.open(input_path) if img.mode != \"L\" and",
"numpy as np from PIL import Image from absl import",
"import FLAGS from ids.voc2012 import get_colormap as get_voc2012_colormap from ids.cityscapes_fine",
"from PIL import Image from absl import app from absl",
"\"voc2012\": colormap = get_voc2012_colormap() elif colormap_name == \"cityscapes\": colormap =",
"elif colormap_name == \"cityscapes\": colormap = get_cityscapes_colormap() else: raise ValueError(f\"Not",
"== 0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap) if __name__",
"colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap) if __name__ == \"__main__\":",
"rootpath) import tensorflow as tf import numpy as np from",
"import tensorflow as tf import numpy as np from PIL",
"output_path = os.path.join(output_dir, filename) img = Image.open(input_path) if img.mode !=",
"img.mode != \"P\": continue img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\")",
"0: colormap = colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap) if __name__ ==",
"filename) output_path = os.path.join(output_dir, filename) img = Image.open(input_path) if img.mode",
"from common_flags import FLAGS from ids.voc2012 import get_colormap as get_voc2012_colormap",
"== \"cityscapes\": colormap = get_cityscapes_colormap() else: raise ValueError(f\"Not support colormap",
"import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir)) sys.path.insert(1, rootpath)",
"from ids.cityscapes_fine import get_colormap as get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir",
"= colormap.astype(np.uint8) counter = 0 if not os.path.exists(output_dir): os.mkdir(output_dir) for",
"get_cityscapes_colormap() else: raise ValueError(f\"Not support colormap = {colormap_name}\") if FLAGS.ignore_label",
"get_cityscapes_colormap flags.DEFINE_string(\"input_dir\", None, \"input dir path\") flags.DEFINE_string(\"output_dir\", None, \"output dir",
"flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap =",
"None, \"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255,",
"and img.mode != \"P\": continue img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path,",
"= FLAGS.colormap colormap_name = colormap_name.lower() if colormap_name == \"voc2012\": colormap",
"================================================================ # MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang)",
"MIT License # Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================",
"apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap = colormap.astype(np.uint8) counter = 0 if",
"ids.voc2012 import get_colormap as get_voc2012_colormap from ids.cityscapes_fine import get_colormap as",
"path\") flags.DEFINE_string(\"output_dir\", None, \"output dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\")",
"== \"voc2012\": colormap = get_voc2012_colormap() elif colormap_name == \"cityscapes\": colormap",
"(https://github.com/edwardyehuang) # ================================================================ import os, sys rootpath = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir,",
"\"L\" and img.mode != \"P\": continue img = img.convert(\"P\") img.putpalette(colormap)",
"Copyright (c) 2021 edwardyehuang (https://github.com/edwardyehuang) # ================================================================ import os, sys",
"from absl import app from absl import flags from common_flags",
"name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\") def apply_colormap_to_dir(input_dir, output_dir=None, colormap=None): colormap",
"\"P\": continue img = img.convert(\"P\") img.putpalette(colormap) img.save(output_path, format=\"PNG\") counter +=",
"dir path\") flags.DEFINE_string(\"colormap\", \"voc2012\", \"colormap name\") flags.DEFINE_integer(\"ignore_label\", 255, \"ignore label\")",
"Image from absl import app from absl import flags from",
"if img.mode != \"L\" and img.mode != \"P\": continue img",
"\"cityscapes\": colormap = get_cityscapes_colormap() else: raise ValueError(f\"Not support colormap =",
"tf.print(\"Processed {}\".format(counter)) def main(argv): colormap_name = FLAGS.colormap colormap_name = colormap_name.lower()",
"None, \"input dir path\") flags.DEFINE_string(\"output_dir\", None, \"output dir path\") flags.DEFINE_string(\"colormap\",",
"flags from common_flags import FLAGS from ids.voc2012 import get_colormap as",
"os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename) img = Image.open(input_path) if",
"= colormap[1:] apply_colormap_to_dir(FLAGS.input_dir, FLAGS.output_dir, colormap=colormap) if __name__ == \"__main__\": app.run(main)",
"= os.path.join(input_dir, filename) output_path = os.path.join(output_dir, filename) img = Image.open(input_path)"
] |
[
"received in the request. :param request: starlette request object \"\"\"",
"<reponame>rit1200/kairon<gh_stars>1-10 class BaseSSO: async def get_redirect_url(self): \"\"\"Returns redirect url for",
"details using code received in the request. :param request: starlette",
"user details using code received in the request. :param request:",
"url for facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\") async def verify(self,",
"request): \"\"\" Fetches user details using code received in the",
"using code received in the request. :param request: starlette request",
"async def verify(self, request): \"\"\" Fetches user details using code",
"facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\") async def verify(self, request): \"\"\"",
"request. :param request: starlette request object \"\"\" raise NotImplementedError(\"Provider not",
"def get_redirect_url(self): \"\"\"Returns redirect url for facebook.\"\"\" raise NotImplementedError(\"Provider not",
"Fetches user details using code received in the request. :param",
"raise NotImplementedError(\"Provider not implemented\") async def verify(self, request): \"\"\" Fetches",
"NotImplementedError(\"Provider not implemented\") async def verify(self, request): \"\"\" Fetches user",
"in the request. :param request: starlette request object \"\"\" raise",
"def verify(self, request): \"\"\" Fetches user details using code received",
"for facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\") async def verify(self, request):",
"the request. :param request: starlette request object \"\"\" raise NotImplementedError(\"Provider",
"BaseSSO: async def get_redirect_url(self): \"\"\"Returns redirect url for facebook.\"\"\" raise",
"not implemented\") async def verify(self, request): \"\"\" Fetches user details",
"code received in the request. :param request: starlette request object",
"class BaseSSO: async def get_redirect_url(self): \"\"\"Returns redirect url for facebook.\"\"\"",
"\"\"\"Returns redirect url for facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\") async",
"\"\"\" Fetches user details using code received in the request.",
"implemented\") async def verify(self, request): \"\"\" Fetches user details using",
"async def get_redirect_url(self): \"\"\"Returns redirect url for facebook.\"\"\" raise NotImplementedError(\"Provider",
"verify(self, request): \"\"\" Fetches user details using code received in",
"redirect url for facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\") async def",
":param request: starlette request object \"\"\" raise NotImplementedError(\"Provider not implemented\")",
"get_redirect_url(self): \"\"\"Returns redirect url for facebook.\"\"\" raise NotImplementedError(\"Provider not implemented\")"
] |
[
"process_journal_change(self, changed_file): if changed_file != self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal)",
"common to everything we shove down the outgoing pipe so",
"FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern =",
"= \"journal.*.log\" logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path):",
"str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1)",
"return keys[-1] def process_journal_change(self, changed_file): if changed_file != self.latest_journal: self.latest_journal",
"import os import glob import logging from pathlib import Path",
"class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass self.journals = {} self.journal_path",
"logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\")",
"file = str(event.src_path) logger.debug(\"Journal moved: \" + file) def _configure_watchers(self):",
"ignore_directories=True) self.on_journal_change = None def set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry",
"distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new entries') for entry in entries:",
"JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False): self.path = path self.force_polling =",
"return all_lines def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file",
"sorted(self.journals.keys()) return keys[-1] def process_journal_change(self, changed_file): if changed_file != self.latest_journal:",
"self._new_journal_entry_callback = None self.latest_journal = self.identify_latest_journal() # Prompter is required",
"self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys()) == 0: return",
"updates on some systems so we get regular updates from",
"'__main__': def ReportJournalChange(journal_hange): print('New route detected:' + str(journal_hange)) journalWatcher =",
"Don't try and read it if this is the first",
"seem to get two; one from the file being cleared).",
"entries = [] if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for",
"from pathlib import Path from watchdog.observers import Observer from watchdog.observers.polling",
"is required to force the file system to do updates",
"Poll every quarter of a second else: self.observer = Observer()",
"pathlib import Path from watchdog.observers import Observer from watchdog.observers.polling import",
"os.stat(changed_file).st_size new_data = None # If the game was loaded",
"to treat as unscanned. if changed_file not in self.journals: self.journals[changed_file]",
"> 0: # Don't try and read it if this",
"entry = json.loads(line) entry['type'] = \"JournalEntry\" # Add an identifier",
"empty line return all_lines def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern))",
"PollingObserver(0.25) # Poll every quarter of a second else: self.observer",
"journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1) except KeyboardInterrupt: print('done') journalWatcher.stop()",
"quarter of a second else: self.observer = Observer() self.observer.schedule(self.event_handler, self.path,",
"binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop",
"new_size except json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii",
"down the outgoing pipe so the receiver can distiguish. entries.append(entry)",
"logger.debug(\"Journal moved: \" + file) def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler()",
"PollingObserver from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path",
"# Check how much it has grown and read the",
"= PollingObserver(0.25) # Poll every quarter of a second else:",
"much it has grown and read the excess size_diff =",
"os.stat(journal_file).st_size class JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False): self.path = path",
"and read it if this is the first notification (we",
"logger.debug(\"Journal change: \" + changed_file) self.on_journal_change(changed_file) def on_created(self, event): file",
"JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in new_journal_lines: logger.debug(f'New journal entry detected:",
"import signature import json import time import os import glob",
"= JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer = PollingObserver(0.25) # Poll every",
"logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]} to {new_size}') if new_size >",
"f: f.seek(-size_diff, os.SEEK_END) # Note minus sign new_data = f.read()",
"def process_journal_change(self, changed_file): if changed_file != self.latest_journal: self.latest_journal = changed_file",
"self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data = None",
"f.seek(-size_diff, os.SEEK_END) # Note minus sign new_data = f.read() entries",
"= str(event.src_path) logger.debug(\"Journal moved: \" + file) def _configure_watchers(self): self.event_handler",
"new_size > 0: # Don't try and read it if",
"all_lines def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in",
"time import os import glob import logging from pathlib import",
"= {} self.journal_path = journal_path logger.debug(f\"watching for journal changes in",
"\"JournalEntry\" # Add an identifier that's common to everything we",
"with open(changed_file, 'rb') as f: f.seek(-size_diff, os.SEEK_END) # Note minus",
"{line}') entry = json.loads(line) entry['type'] = \"JournalEntry\" # Add an",
"journal_file in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher: def __init__(self,",
"get regular updates from the # journal watcher. self.prompter =",
"keys = sorted(self.journals.keys()) return keys[-1] def process_journal_change(self, changed_file): if changed_file",
"e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines =",
"event): changed_file = str(event.src_path) logger.debug(\"Journal change: \" + changed_file) self.on_journal_change(changed_file)",
"the file system to do updates on some systems so",
"self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data =",
"an identifier that's common to everything we shove down the",
"signature import json import time import os import glob import",
"+ changed_file) self.on_journal_change(changed_file) def on_created(self, event): file = str(event.src_path) logger.debug(\"Journal",
"class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change",
"journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False):",
"Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if __name__ == '__main__': def",
"[] if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in",
"<gh_stars>0 from inspect import signature import json import time import",
"new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in new_journal_lines: logger.debug(f'New",
"path=default_journal_path, force_polling=False): self.path = path self.force_polling = force_polling self._configure_watchers() def",
"Note minus sign new_data = f.read() entries = [] if",
"self.force_polling = force_polling self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self):",
"a second else: self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start()",
"entries') for entry in entries: yield entry self.journals[changed_file] = new_size",
"+ str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True:",
"new_data = f.read() entries = [] if new_data: new_journal_lines =",
"import logging from pathlib import Path from watchdog.observers import Observer",
"import PollingObserver from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter",
"Dangerous\") journal_file_pattern = \"journal.*.log\" logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier: def",
"in entries: yield entry self.journals[changed_file] = new_size except json.decoder.JSONDecodeError as",
"changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data = None # If",
"it will start a new journal which we need to",
"file) def on_moved(self, event): file = str(event.src_path) logger.debug(\"Journal moved: \"",
"= [] if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line",
"import Path from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver",
"self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if __name__ == '__main__': def ReportJournalChange(journal_hange):",
"from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path =",
"= on_new_journal_entry def on_modified(self, event): changed_file = str(event.src_path) logger.debug(\"Journal change:",
"patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change = None def set_callback(self, on_new_journal_entry): self.on_journal_change",
"the last empty line return all_lines def _init_journal_lists(self): journal_files =",
"logging from pathlib import Path from watchdog.observers import Observer from",
"to force the file system to do updates on some",
"= \"JournalEntry\" # Add an identifier that's common to everything",
"we shove down the outgoing pipe so the receiver can",
"watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import",
"regular updates from the # journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal)",
"in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal = self.identify_latest_journal() #",
"detected: {line}') entry = json.loads(line) entry['type'] = \"JournalEntry\" # Add",
"excess size_diff = new_size - self.journals[changed_file] if size_diff > 0:",
"_configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer = PollingObserver(0.25) #",
"{self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal = self.identify_latest_journal() # Prompter",
"detected:' + str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while",
"journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1) except",
"self.journals[changed_file] if size_diff > 0: with open(changed_file, 'rb') as f:",
"one from the file being cleared). # Check how much",
"self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change = None def set_callback(self, on_new_journal_entry):",
"# Drop the last empty line return all_lines def _init_journal_lists(self):",
"new entries') for entry in entries: yield entry self.journals[changed_file] =",
"required to force the file system to do updates on",
"entries: yield entry self.journals[changed_file] = new_size except json.decoder.JSONDecodeError as e:",
"= JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1) except KeyboardInterrupt:",
"= glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size",
"in new_journal_lines: logger.debug(f'New journal entry detected: {line}') entry = json.loads(line)",
"second else: self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if",
"treat as unscanned. if changed_file not in self.journals: self.journals[changed_file] =",
"the scout it will start a new journal which we",
"the file being cleared). # Check how much it has",
"on_moved(self, event): file = str(event.src_path) logger.debug(\"Journal moved: \" + file)",
"None self.latest_journal = self.identify_latest_journal() # Prompter is required to force",
"+ file) def on_deleted(self, event): file = str(event.src_path) logger.debug(\"Journal deleted:",
"\"journal.*.log\" logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass",
"changed_file) self.on_journal_change(changed_file) def on_created(self, event): file = str(event.src_path) logger.debug(\"Journal created:",
"self.journals = {} self.journal_path = journal_path logger.debug(f\"watching for journal changes",
"= f.read() entries = [] if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data)",
"created: \" + file) def on_deleted(self, event): file = str(event.src_path)",
"__name__ == '__main__': def ReportJournalChange(journal_hange): print('New route detected:' + str(journal_hange))",
"None def set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry def on_modified(self, event):",
"as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the last empty line return all_lines",
"def stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__(",
"last empty line return all_lines def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path,",
"logger.debug(\"Journal deleted: \" + file) def on_moved(self, event): file =",
"print('New route detected:' + str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running')",
"None # If the game was loaded after the scout",
"journal_path logger.debug(f\"watching for journal changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback =",
"cleared). # Check how much it has grown and read",
"f.read() entries = [] if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try:",
"= sorted(self.journals.keys()) return keys[-1] def process_journal_change(self, changed_file): if changed_file !=",
"= None self.latest_journal = self.identify_latest_journal() # Prompter is required to",
"if len(self.journals.keys()) == 0: return None keys = sorted(self.journals.keys()) return",
"new journal which we need to treat as unscanned. if",
"if new_size > 0: # Don't try and read it",
"= force_polling self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop()",
"\"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\" logger = logging.getLogger('JournalInterface')",
"def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler):",
"def on_modified(self, event): changed_file = str(event.src_path) logger.debug(\"Journal change: \" +",
"= journal_path logger.debug(f\"watching for journal changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback",
"notification (we seem to get two; one from the file",
"{} self.journal_path = journal_path logger.debug(f\"watching for journal changes in {self.journal_path}\")",
"game was loaded after the scout it will start a",
"self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True)",
"journal_file_pattern = \"journal.*.log\" logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self,",
"on_deleted(self, event): file = str(event.src_path) logger.debug(\"Journal deleted: \" + file)",
"import json import time import os import glob import logging",
"if size_diff > 0: with open(changed_file, 'rb') as f: f.seek(-size_diff,",
"size_diff = new_size - self.journals[changed_file] if size_diff > 0: with",
"outgoing pipe so the receiver can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)}",
"0: return None keys = sorted(self.journals.keys()) return keys[-1] def process_journal_change(self,",
"self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False): self.path",
"def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() #",
"def ReportJournalChange(journal_hange): print('New route detected:' + str(journal_hange)) journalWatcher = JournalWatcher()",
"on_new_journal_entry): self.on_journal_change = on_new_journal_entry def on_modified(self, event): changed_file = str(event.src_path)",
"Drop the last empty line return all_lines def _init_journal_lists(self): journal_files",
"grown and read the excess size_diff = new_size - self.journals[changed_file]",
"the receiver can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new entries') for",
"recursive=False) self.observer.start() if __name__ == '__main__': def ReportJournalChange(journal_hange): print('New route",
"unscanned. if changed_file not in self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file}",
"some systems so we get regular updates from the #",
"from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from watchdog.events",
"= 0 logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]} to {new_size}') if",
"journal changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal =",
"in self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]}",
"\" + file) def on_deleted(self, event): file = str(event.src_path) logger.debug(\"Journal",
"= self.identify_latest_journal() # Prompter is required to force the file",
"set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def",
"Add an identifier that's common to everything we shove down",
"def on_deleted(self, event): file = str(event.src_path) logger.debug(\"Journal deleted: \" +",
"self.on_journal_change(changed_file) def on_created(self, event): file = str(event.src_path) logger.debug(\"Journal created: \"",
"for entry in entries: yield entry self.journals[changed_file] = new_size except",
"do updates on some systems so we get regular updates",
"it has grown and read the excess size_diff = new_size",
"from inspect import signature import json import time import os",
"sign new_data = f.read() entries = [] if new_data: new_journal_lines",
"len(self.journals.keys()) == 0: return None keys = sorted(self.journals.keys()) return keys[-1]",
"file system to do updates on some systems so we",
"as unscanned. if changed_file not in self.journals: self.journals[changed_file] = 0",
"change: {self.journals[changed_file]} to {new_size}') if new_size > 0: # Don't",
"file) def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer =",
"entry in entries: yield entry self.journals[changed_file] = new_size except json.decoder.JSONDecodeError",
"def identify_latest_journal(self): if len(self.journals.keys()) == 0: return None keys =",
"we need to treat as unscanned. if changed_file not in",
"has grown and read the excess size_diff = new_size -",
"class JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False): self.path = path self.force_polling",
"self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal = self.identify_latest_journal() # Prompter is",
"new_size = os.stat(changed_file).st_size new_data = None # If the game",
"to everything we shove down the outgoing pipe so the",
"logger.debug(\"Journal created: \" + file) def on_deleted(self, event): file =",
"import glob import logging from pathlib import Path from watchdog.observers",
"self.path = path self.force_polling = force_polling self._configure_watchers() def set_callback(self, on_journal_change):",
"if self.force_polling: self.observer = PollingObserver(0.25) # Poll every quarter of",
"self.journal_path = journal_path logger.debug(f\"watching for journal changes in {self.journal_path}\") self._init_journal_lists()",
"except json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii =",
"== 0: return None keys = sorted(self.journals.keys()) return keys[-1] def",
"file = str(event.src_path) logger.debug(\"Journal created: \" + file) def on_deleted(self,",
"0 logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]} to {new_size}') if new_size",
"= FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys()) == 0: return None",
"that's common to everything we shove down the outgoing pipe",
"line return all_lines def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for",
"if this is the first notification (we seem to get",
"journal_file_pattern)) for journal_file in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher:",
"Check how much it has grown and read the excess",
"import Observer from watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler",
"on_new_journal_entry def on_modified(self, event): changed_file = str(event.src_path) logger.debug(\"Journal change: \"",
"\" + file) def on_moved(self, event): file = str(event.src_path) logger.debug(\"Journal",
"= os.stat(changed_file).st_size new_data = None # If the game was",
"start a new journal which we need to treat as",
"file = str(event.src_path) logger.debug(\"Journal deleted: \" + file) def on_moved(self,",
"changed_file != self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size",
"not in self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file} - Size change:",
"minus sign new_data = f.read() entries = [] if new_data:",
"entry detected: {line}') entry = json.loads(line) entry['type'] = \"JournalEntry\" #",
"{self.journals[changed_file]} to {new_size}') if new_size > 0: # Don't try",
"import time import os import glob import logging from pathlib",
"read the excess size_diff = new_size - self.journals[changed_file] if size_diff",
"all_lines.pop() # Drop the last empty line return all_lines def",
"event): file = str(event.src_path) logger.debug(\"Journal moved: \" + file) def",
"of a second else: self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=False)",
"try and read it if this is the first notification",
"scout it will start a new journal which we need",
"ReportJournalChange(journal_hange): print('New route detected:' + str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange)",
"# Prompter is required to force the file system to",
"else: self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if __name__",
"keys[-1] def process_journal_change(self, changed_file): if changed_file != self.latest_journal: self.latest_journal =",
"for line in new_journal_lines: logger.debug(f'New journal entry detected: {line}') entry",
"file being cleared). # Check how much it has grown",
"0: with open(changed_file, 'rb') as f: f.seek(-size_diff, os.SEEK_END) # Note",
"0: # Don't try and read it if this is",
"+ file) def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer",
"self.observer.start() if __name__ == '__main__': def ReportJournalChange(journal_hange): print('New route detected:'",
"watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()),",
"import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved",
"event): file = str(event.src_path) logger.debug(\"Journal deleted: \" + file) def",
"= str(event.src_path) logger.debug(\"Journal deleted: \" + file) def on_moved(self, event):",
"# Don't try and read it if this is the",
"self.observer = Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if __name__ ==",
"os.SEEK_END) # Note minus sign new_data = f.read() entries =",
"on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self):",
"= new_size except json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data):",
"new_journal_lines: logger.debug(f'New journal entry detected: {line}') entry = json.loads(line) entry['type']",
"updates from the # journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def",
"str(event.src_path) logger.debug(\"Journal deleted: \" + file) def on_moved(self, event): file",
"two; one from the file being cleared). # Check how",
"for journal changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal",
"== '__main__': def ReportJournalChange(journal_hange): print('New route detected:' + str(journal_hange)) journalWatcher",
"as_ascii = binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the",
"# Add an identifier that's common to everything we shove",
"= None def set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry def on_modified(self,",
"If the game was loaded after the scout it will",
"__init__(self, journal_path=default_journal_path): pass self.journals = {} self.journal_path = journal_path logger.debug(f\"watching",
"the outgoing pipe so the receiver can distiguish. entries.append(entry) logger.debug(f'Found",
"logger.debug(f'Found {len(entries)} new entries') for entry in entries: yield entry",
"self.latest_journal = self.identify_latest_journal() # Prompter is required to force the",
"self.on_journal_change = on_new_journal_entry def on_modified(self, event): changed_file = str(event.src_path) logger.debug(\"Journal",
"so we get regular updates from the # journal watcher.",
"logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass self.journals = {}",
"logger.debug(f'New journal entry detected: {line}') entry = json.loads(line) entry['type'] =",
"entry self.journals[changed_file] = new_size except json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod",
"first notification (we seem to get two; one from the",
"journal entry detected: {line}') entry = json.loads(line) entry['type'] = \"JournalEntry\"",
"stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'],",
"force_polling=False): self.path = path self.force_polling = force_polling self._configure_watchers() def set_callback(self,",
"def __init__(self, journal_path=default_journal_path): pass self.journals = {} self.journal_path = journal_path",
"if new_data: new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in new_journal_lines:",
"= binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the last",
"str(event.src_path) logger.debug(\"Journal change: \" + changed_file) self.on_journal_change(changed_file) def on_created(self, event):",
"{new_size}') if new_size > 0: # Don't try and read",
"receiver can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new entries') for entry",
"= new_size - self.journals[changed_file] if size_diff > 0: with open(changed_file,",
"def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer = PollingObserver(0.25)",
"os import glob import logging from pathlib import Path from",
"watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from watchdog.events import",
"it if this is the first notification (we seem to",
"- Size change: {self.journals[changed_file]} to {new_size}') if new_size > 0:",
"= os.stat(journal_file).st_size class JournalWatcher: def __init__(self, path=default_journal_path, force_polling=False): self.path =",
"json import time import os import glob import logging from",
"glob import logging from pathlib import Path from watchdog.observers import",
"# journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys())",
"= JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in new_journal_lines: logger.debug(f'New journal entry",
"we get regular updates from the # journal watcher. self.prompter",
"glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class",
"None keys = sorted(self.journals.keys()) return keys[-1] def process_journal_change(self, changed_file): if",
"pipe so the receiver can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new",
"change: \" + changed_file) self.on_journal_change(changed_file) def on_created(self, event): file =",
"from the # journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self):",
"so the receiver can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new entries')",
"Observer from watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler from",
"try: for line in new_journal_lines: logger.debug(f'New journal entry detected: {line}')",
"identifier that's common to everything we shove down the outgoing",
"= Observer() self.observer.schedule(self.event_handler, self.path, recursive=False) self.observer.start() if __name__ == '__main__':",
"on some systems so we get regular updates from the",
"def on_moved(self, event): file = str(event.src_path) logger.debug(\"Journal moved: \" +",
"journal which we need to treat as unscanned. if changed_file",
"self.observer = PollingObserver(0.25) # Poll every quarter of a second",
"logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass self.journals",
"the game was loaded after the scout it will start",
"def __init__(self, path=default_journal_path, force_polling=False): self.path = path self.force_polling = force_polling",
"{len(entries)} new entries') for entry in entries: yield entry self.journals[changed_file]",
"default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\"",
"JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass self.journals = {} self.journal_path =",
"+ file) def on_moved(self, event): file = str(event.src_path) logger.debug(\"Journal moved:",
"changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None self.latest_journal = self.identify_latest_journal()",
"# Poll every quarter of a second else: self.observer =",
"is the first notification (we seem to get two; one",
"Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\" logger = logging.getLogger('JournalInterface') class",
"self.force_polling: self.observer = PollingObserver(0.25) # Poll every quarter of a",
"how much it has grown and read the excess size_diff",
"Prompter is required to force the file system to do",
"event): file = str(event.src_path) logger.debug(\"Journal created: \" + file) def",
"force the file system to do updates on some systems",
"json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8')",
"journal_path=default_journal_path): pass self.journals = {} self.journal_path = journal_path logger.debug(f\"watching for",
"set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry def on_modified(self, event): changed_file =",
"(we seem to get two; one from the file being",
"__init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change = None def",
"= str(event.src_path) logger.debug(\"Journal change: \" + changed_file) self.on_journal_change(changed_file) def on_created(self,",
"os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\" logger =",
"binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the last empty",
"inspect import signature import json import time import os import",
"this is the first notification (we seem to get two;",
"= None # If the game was loaded after the",
"new_size - self.journals[changed_file] if size_diff > 0: with open(changed_file, 'rb')",
"watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys()) == 0:",
"Size change: {self.journals[changed_file]} to {new_size}') if new_size > 0: #",
"_init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in journal_files: self.journals[journal_file]",
"def on_created(self, event): file = str(event.src_path) logger.debug(\"Journal created: \" +",
"if __name__ == '__main__': def ReportJournalChange(journal_hange): print('New route detected:' +",
"entries.append(entry) logger.debug(f'Found {len(entries)} new entries') for entry in entries: yield",
"\" + changed_file) self.on_journal_change(changed_file) def on_created(self, event): file = str(event.src_path)",
"new_journal_lines = JournalChangeIdentifier.binary_file_data_to_lines(new_data) try: for line in new_journal_lines: logger.debug(f'New journal",
"for journal_file in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher: def",
"self.on_journal_change = None def set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry def",
"to get two; one from the file being cleared). #",
"journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in journal_files: self.journals[journal_file] =",
"from watchdog.observers.polling import PollingObserver from watchdog.events import PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter",
"changed_file): if changed_file != self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size",
"get two; one from the file being cleared). # Check",
"open(changed_file, 'rb') as f: f.seek(-size_diff, os.SEEK_END) # Note minus sign",
"= os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\" logger",
"line in new_journal_lines: logger.debug(f'New journal entry detected: {line}') entry =",
"Developments\\\\Elite Dangerous\") journal_file_pattern = \"journal.*.log\" logger = logging.getLogger('JournalInterface') class JournalChangeIdentifier:",
"which we need to treat as unscanned. if changed_file not",
"= json.loads(line) entry['type'] = \"JournalEntry\" # Add an identifier that's",
"> 0: with open(changed_file, 'rb') as f: f.seek(-size_diff, os.SEEK_END) #",
"entry['type'] = \"JournalEntry\" # Add an identifier that's common to",
"everything we shove down the outgoing pipe so the receiver",
"= logging.getLogger('JournalInterface') class JournalChangeIdentifier: def __init__(self, journal_path=default_journal_path): pass self.journals =",
"if changed_file != self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size =",
"self.journals[changed_file] = 0 logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]} to {new_size}')",
"from the file being cleared). # Check how much it",
"# Note minus sign new_data = f.read() entries = []",
"every quarter of a second else: self.observer = Observer() self.observer.schedule(self.event_handler,",
"self.identify_latest_journal() # Prompter is required to force the file system",
"to do updates on some systems so we get regular",
"return None keys = sorted(self.journals.keys()) return keys[-1] def process_journal_change(self, changed_file):",
"self.path, recursive=False) self.observer.start() if __name__ == '__main__': def ReportJournalChange(journal_hange): print('New",
"if changed_file not in self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file} -",
"the excess size_diff = new_size - self.journals[changed_file] if size_diff >",
"'rb') as f: f.seek(-size_diff, os.SEEK_END) # Note minus sign new_data",
"= as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the last empty line return",
"self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[],",
"shove down the outgoing pipe so the receiver can distiguish.",
"def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change = None",
"FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys()) == 0: return None keys",
"all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop() # Drop the last empty line",
"size_diff > 0: with open(changed_file, 'rb') as f: f.seek(-size_diff, os.SEEK_END)",
"Path from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver from",
"after the scout it will start a new journal which",
"self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer = PollingObserver(0.25) # Poll",
"identify_latest_journal(self): if len(self.journals.keys()) == 0: return None keys = sorted(self.journals.keys())",
"route detected:' + str(journal_hange)) journalWatcher = JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try:",
"json.loads(line) entry['type'] = \"JournalEntry\" # Add an identifier that's common",
"def _init_journal_lists(self): journal_files = glob.glob(os.path.join(self.journal_path, journal_file_pattern)) for journal_file in journal_files:",
"need to treat as unscanned. if changed_file not in self.journals:",
"= path self.force_polling = force_polling self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change)",
"PatternMatchingEventHandler from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier",
"EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\")",
"and read the excess size_diff = new_size - self.journals[changed_file] if",
"as e: logger.exception(e) @staticmethod def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines",
"_EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change =",
"on_modified(self, event): changed_file = str(event.src_path) logger.debug(\"Journal change: \" + changed_file)",
"deleted: \" + file) def on_moved(self, event): file = str(event.src_path)",
"can distiguish. entries.append(entry) logger.debug(f'Found {len(entries)} new entries') for entry in",
"str(event.src_path) logger.debug(\"Journal created: \" + file) def on_deleted(self, event): file",
"self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join() class _EntriesChangeHandler(PatternMatchingEventHandler): def __init__(self): super(JournalWatcher._EntriesChangeHandler,",
"logger.debug(f\"watching for journal changes in {self.journal_path}\") self._init_journal_lists() self._new_journal_entry_callback = None",
"import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite Dangerous\") journal_file_pattern",
"path self.force_polling = force_polling self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def",
"force_polling self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join()",
"self._configure_watchers() def set_callback(self, on_journal_change): self.event_handler.set_callback(on_journal_change) def stop(self): self.observer.stop() self.observer.join() class",
"was loaded after the scout it will start a new",
"\" + file) def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if self.force_polling:",
"a new journal which we need to treat as unscanned.",
"moved: \" + file) def _configure_watchers(self): self.event_handler = JournalWatcher._EntriesChangeHandler() if",
"changed_file = str(event.src_path) logger.debug(\"Journal change: \" + changed_file) self.on_journal_change(changed_file) def",
"new_data = None # If the game was loaded after",
"__init__(self, path=default_journal_path, force_polling=False): self.path = path self.force_polling = force_polling self._configure_watchers()",
"= str(event.src_path) logger.debug(\"Journal created: \" + file) def on_deleted(self, event):",
"JournalWatcher._EntriesChangeHandler() if self.force_polling: self.observer = PollingObserver(0.25) # Poll every quarter",
"as f: f.seek(-size_diff, os.SEEK_END) # Note minus sign new_data =",
"will start a new journal which we need to treat",
"# If the game was loaded after the scout it",
"file) def on_deleted(self, event): file = str(event.src_path) logger.debug(\"Journal deleted: \"",
"self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data = None # If the",
"loaded after the scout it will start a new journal",
"on_created(self, event): file = str(event.src_path) logger.debug(\"Journal created: \" + file)",
"str(event.src_path) logger.debug(\"Journal moved: \" + file) def _configure_watchers(self): self.event_handler =",
"@staticmethod def binary_file_data_to_lines(binary_data): as_ascii = binary_data.decode('UTF-8') all_lines = as_ascii.split(\"\\r\\n\") all_lines.pop()",
"super(JournalWatcher._EntriesChangeHandler, self).__init__( patterns=['*Journal*.log'], ignore_patterns=[], ignore_directories=True) self.on_journal_change = None def set_callback(self,",
"the first notification (we seem to get two; one from",
"changed_file not in self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file} - Size",
"the # journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if",
"in journal_files: self.journals[journal_file] = os.stat(journal_file).st_size class JournalWatcher: def __init__(self, path=default_journal_path,",
"journal watcher. self.prompter = FileSystemUpdatePrompter(self.latest_journal) def identify_latest_journal(self): if len(self.journals.keys()) ==",
"def set_callback(self, on_new_journal_entry): self.on_journal_change = on_new_journal_entry def on_modified(self, event): changed_file",
"self.journals[changed_file] = new_size except json.decoder.JSONDecodeError as e: logger.exception(e) @staticmethod def",
"- self.journals[changed_file] if size_diff > 0: with open(changed_file, 'rb') as",
"yield entry self.journals[changed_file] = new_size except json.decoder.JSONDecodeError as e: logger.exception(e)",
"system to do updates on some systems so we get",
"= changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data = None #",
"JournalWatcher() journalWatcher.set_callback(ReportJournalChange) print('running') try: while True: time.sleep(1) except KeyboardInterrupt: print('done')",
"being cleared). # Check how much it has grown and",
"from EDScoutCore.FileSystemUpdatePrompter import FileSystemUpdatePrompter default_journal_path = os.path.join(str(Path.home()), \"Saved Games\\\\Frontier Developments\\\\Elite",
"ignore_patterns=[], ignore_directories=True) self.on_journal_change = None def set_callback(self, on_new_journal_entry): self.on_journal_change =",
"!= self.latest_journal: self.latest_journal = changed_file self.prompter.set_watch_file(self.latest_journal) new_size = os.stat(changed_file).st_size new_data",
"self.journals: self.journals[changed_file] = 0 logger.debug(f'{changed_file} - Size change: {self.journals[changed_file]} to",
"read it if this is the first notification (we seem",
"pass self.journals = {} self.journal_path = journal_path logger.debug(f\"watching for journal",
"systems so we get regular updates from the # journal",
"to {new_size}') if new_size > 0: # Don't try and"
] |
[
"os.path.basename(dir_path) id_location = 0 id_file = 0 for dir_file in",
"h.hexdigest() def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path)",
"file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info VALUES (?, ?, ?, ?,",
"= (id_location, file_path) c.execute(\"INSERT INTO location VALUES (?, ?)\", location_values)",
"sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() import os import",
"= os.path.realpath(dir_file) location_values = (id_location, file_path) c.execute(\"INSERT INTO location VALUES",
"dir_file file_md5 = get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size = os.path.getsize(dir_file)",
"time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path = os.path.realpath(dir_file) location_values = (id_location,",
"sqlite3.connect('example.db') c = conn.cursor() import os import hashlib import time",
"id_file += 1 get_dir_data('./') # Save (commit) the changes conn.commit()",
"= (id_location, id_file) c.execute(\"INSERT INTO files VALUES (?, ?)\", files_values)",
"VALUES (?, ?, ?, ?, ?)\", file_info_values) id_location += 1",
"get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file))",
"location_values) files_values = (id_location, id_file) c.execute(\"INSERT INTO files VALUES (?,",
"INTO location VALUES (?, ?)\", location_values) files_values = (id_location, id_file)",
"?, ?, ?, ?)\", file_info_values) id_location += 1 id_file +=",
"os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time)",
"file_sha256 = get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time",
"= get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time =",
"get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location =",
"import time def get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest()",
"= hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path)",
"file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path = os.path.realpath(dir_file) location_values",
"INTO file_info VALUES (?, ?, ?, ?, ?)\", file_info_values) id_location",
"os import hashlib import time def get_file_md5(filePath): h = hashlib.md5()",
"conn.cursor() import os import hashlib import time def get_file_md5(filePath): h",
"= conn.cursor() import os import hashlib import time def get_file_md5(filePath):",
"dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location = 0",
"h.hexdigest() def get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def",
"= time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path = os.path.realpath(dir_file) location_values =",
"h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2]",
"= sqlite3.connect('example.db') c = conn.cursor() import os import hashlib import",
"#print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location = 0 id_file = 0",
"hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read())",
"(?, ?, ?, ?, ?)\", file_info_values) id_location += 1 id_file",
"(id_location, id_file) c.execute(\"INSERT INTO files VALUES (?, ?)\", files_values) file_info_values",
"return h.hexdigest() def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print",
"file_info_values) id_location += 1 id_file += 1 get_dir_data('./') # Save",
"return h.hexdigest() def get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest()",
"(?, ?)\", files_values) file_info_values = (id_file, file_name, file_size, file_formatted_time, file_md5)",
"= 0 id_file = 0 for dir_file in next(os.walk(dir_path))[2]: file_name",
"file_path) c.execute(\"INSERT INTO location VALUES (?, ?)\", location_values) files_values =",
"file_md5) c.execute(\"INSERT INTO file_info VALUES (?, ?, ?, ?, ?)\",",
"file_info VALUES (?, ?, ?, ?, ?)\", file_info_values) id_location +=",
"+= 1 id_file += 1 get_dir_data('./') # Save (commit) the",
"?, ?)\", file_info_values) id_location += 1 id_file += 1 get_dir_data('./')",
"time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path = os.path.realpath(dir_file)",
"file_size = os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S",
"#print os.path.basename(dir_path) id_location = 0 id_file = 0 for dir_file",
"file_md5 = get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time",
"file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info VALUES (?, ?,",
"= 0 for dir_file in next(os.walk(dir_path))[2]: file_name = dir_file file_md5",
"0 for dir_file in next(os.walk(dir_path))[2]: file_name = dir_file file_md5 =",
"import sqlite3 conn = sqlite3.connect('example.db') c = conn.cursor() import os",
"h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path): dir_path =",
"id_location += 1 id_file += 1 get_dir_data('./') # Save (commit)",
"c = conn.cursor() import os import hashlib import time def",
"next(os.walk(dir_path))[2]: file_name = dir_file file_md5 = get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file)",
"id_file) c.execute(\"INSERT INTO files VALUES (?, ?)\", files_values) file_info_values =",
"files_values = (id_location, id_file) c.execute(\"INSERT INTO files VALUES (?, ?)\",",
"h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return",
"next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location = 0 id_file = 0 for",
"(?, ?)\", location_values) files_values = (id_location, id_file) c.execute(\"INSERT INTO files",
"?)\", files_values) file_info_values = (id_file, file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT",
"files_values) file_info_values = (id_file, file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO",
"location_values = (id_location, file_path) c.execute(\"INSERT INTO location VALUES (?, ?)\",",
"id_location = 0 id_file = 0 for dir_file in next(os.walk(dir_path))[2]:",
"0 id_file = 0 for dir_file in next(os.walk(dir_path))[2]: file_name =",
"get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d",
"hashlib import time def get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return",
"location VALUES (?, ?)\", location_values) files_values = (id_location, id_file) c.execute(\"INSERT",
"= os.path.getsize(dir_file) file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\",",
"file_info_values = (id_file, file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info",
"time def get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def",
"h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath): h =",
"dir_file in next(os.walk(dir_path))[2]: file_name = dir_file file_md5 = get_file_md5(dir_file) file_sha256",
"get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath): h",
"(id_file, file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info VALUES (?,",
"INTO files VALUES (?, ?)\", files_values) file_info_values = (id_file, file_name,",
"c.execute(\"INSERT INTO location VALUES (?, ?)\", location_values) files_values = (id_location,",
"import hashlib import time def get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read())",
"hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print",
"conn = sqlite3.connect('example.db') c = conn.cursor() import os import hashlib",
"def get_file_md5(filePath): h = hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath):",
"?, ?, ?)\", file_info_values) id_location += 1 id_file += 1",
"= (id_file, file_name, file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info VALUES",
"= dir_file file_md5 = get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size =",
"for dir_file in next(os.walk(dir_path))[2]: file_name = dir_file file_md5 = get_file_md5(dir_file)",
"%I:%M:%S %p\", file_time) file_path = os.path.realpath(dir_file) location_values = (id_location, file_path)",
"id_file = 0 for dir_file in next(os.walk(dir_path))[2]: file_name = dir_file",
"in next(os.walk(dir_path))[2]: file_name = dir_file file_md5 = get_file_md5(dir_file) file_sha256 =",
"= time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path =",
"VALUES (?, ?)\", files_values) file_info_values = (id_file, file_name, file_size, file_formatted_time,",
"file_name = dir_file file_md5 = get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size",
"c.execute(\"INSERT INTO file_info VALUES (?, ?, ?, ?, ?)\", file_info_values)",
"(id_location, file_path) c.execute(\"INSERT INTO location VALUES (?, ?)\", location_values) files_values",
"file_path = os.path.realpath(dir_file) location_values = (id_location, file_path) c.execute(\"INSERT INTO location",
"os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location = 0 id_file =",
"file_time) file_path = os.path.realpath(dir_file) location_values = (id_location, file_path) c.execute(\"INSERT INTO",
"files VALUES (?, ?)\", files_values) file_info_values = (id_file, file_name, file_size,",
"?)\", location_values) files_values = (id_location, id_file) c.execute(\"INSERT INTO files VALUES",
"file_time = time.gmtime(os.path.getctime(dir_file)) file_formatted_time = time.strftime(\"%Y-%m-%d %I:%M:%S %p\", file_time) file_path",
"= hashlib.md5() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_file_sha256(filePath): h = hashlib.sha256()",
"?)\", file_info_values) id_location += 1 id_file += 1 get_dir_data('./') #",
"os.path.realpath(dir_file) location_values = (id_location, file_path) c.execute(\"INSERT INTO location VALUES (?,",
"import os import hashlib import time def get_file_md5(filePath): h =",
"def get_dir_data(dir_path): dir_path = os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location",
"c.execute(\"INSERT INTO files VALUES (?, ?)\", files_values) file_info_values = (id_file,",
"1 id_file += 1 get_dir_data('./') # Save (commit) the changes",
"VALUES (?, ?)\", location_values) files_values = (id_location, id_file) c.execute(\"INSERT INTO",
"def get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path):",
"file_size, file_formatted_time, file_md5) c.execute(\"INSERT INTO file_info VALUES (?, ?, ?,",
"= get_file_md5(dir_file) file_sha256 = get_file_sha256(dir_file) file_size = os.path.getsize(dir_file) file_time =",
"get_file_sha256(filePath): h = hashlib.sha256() h.update(open(filePath,\"rb\").read()) return h.hexdigest() def get_dir_data(dir_path): dir_path",
"%p\", file_time) file_path = os.path.realpath(dir_file) location_values = (id_location, file_path) c.execute(\"INSERT",
"= os.path.realpath(dir_path) #print next(os.walk(dir_path))[2] #print os.path.basename(dir_path) id_location = 0 id_file",
"+= 1 get_dir_data('./') # Save (commit) the changes conn.commit() conn.close()"
] |
[
"migrate_engine print __doc__ metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata,",
"metadata.bind = migrate_engine print __doc__ metadata.reflect() try: Implicitly_converted_table = Table(",
"c = Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True",
"failed: %s\" % str( e ) ) def downgrade(migrate_engine): metadata.bind",
"print \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\" %",
"\"implicitly_converted_dataset_association\", metadata, autoload=True ) if migrate_engine.name != 'sqlite': c =",
"table failed: %s\" % str( e ) ) def downgrade(migrate_engine):",
") else: #Can't use the ForeignKey in sqlite. c =",
"\"\"\" from sqlalchemy import * from sqlalchemy.orm import * from",
"metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print \"Dropping ldda_parent_id",
"* from sqlalchemy.orm import * from migrate import * from",
"implicitly_converted_dataset_association table failed: %s\" % str( e ) log.debug( \"Dropping",
"implicitly_converted_dataset_association table. \"\"\" from sqlalchemy import * from sqlalchemy.orm import",
"metadata, autoload=True ) if migrate_engine.name != 'sqlite': c = Column(",
"metadata = MetaData() def upgrade(migrate_engine): metadata.bind = migrate_engine print __doc__",
"except Exception, e: print \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table",
") c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id except Exception,",
"index=True, nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id",
"\"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True ) else: #Can't",
"= Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True )",
"migrate_engine.name != 'sqlite': c = Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\"",
"str( e ) ) def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect()",
"from implicitly_converted_dataset_association table failed: %s\" % str( e ) )",
"%s\" % str( e ) log.debug( \"Adding ldda_parent_id column to",
"!= 'sqlite': c = Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ),",
"\"library_dataset_dataset_association.id\" ), index=True, nullable=True ) else: #Can't use the ForeignKey",
") Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print \"Dropping ldda_parent_id column from",
"try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) if migrate_engine.name",
"metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop()",
"= migrate_engine metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True",
"def upgrade(migrate_engine): metadata.bind = migrate_engine print __doc__ metadata.reflect() try: Implicitly_converted_table",
") ) def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() try: Implicitly_converted_table",
"#Can't use the ForeignKey in sqlite. c = Column( \"ldda_parent_id\",",
"% str( e ) log.debug( \"Adding ldda_parent_id column to implicitly_converted_dataset_association",
"= MetaData() def upgrade(migrate_engine): metadata.bind = migrate_engine print __doc__ metadata.reflect()",
"sqlalchemy.orm import * from migrate import * from migrate.changeset import",
"ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True ) else: #Can't use the",
"log.debug( \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\" %",
"Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception,",
"if migrate_engine.name != 'sqlite': c = Column( \"ldda_parent_id\", Integer, ForeignKey(",
"to the implicitly_converted_dataset_association table. \"\"\" from sqlalchemy import * from",
"nullable=True ) else: #Can't use the ForeignKey in sqlite. c",
"e: print \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\"",
"upgrade(migrate_engine): metadata.bind = migrate_engine print __doc__ metadata.reflect() try: Implicitly_converted_table =",
"import * import logging log = logging.getLogger( __name__ ) metadata",
"str( e ) log.debug( \"Adding ldda_parent_id column to implicitly_converted_dataset_association table",
"e ) ) def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() try:",
"Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print",
"column from implicitly_converted_dataset_association table failed: %s\" % str( e )",
"import * from migrate.changeset import * import logging log =",
"\"ldda_parent_id\", Integer, index=True, nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c",
"= Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e:",
"add 'ldda_parent_id' column to the implicitly_converted_dataset_association table. \"\"\" from sqlalchemy",
"downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\",",
"Migration script to add 'ldda_parent_id' column to the implicitly_converted_dataset_association table.",
"MetaData() def upgrade(migrate_engine): metadata.bind = migrate_engine print __doc__ metadata.reflect() try:",
"logging log = logging.getLogger( __name__ ) metadata = MetaData() def",
"__name__ ) metadata = MetaData() def upgrade(migrate_engine): metadata.bind = migrate_engine",
"Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id except Exception, e: print",
"* from migrate import * from migrate.changeset import * import",
"column to implicitly_converted_dataset_association table failed: %s\" % str( e )",
"index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id except Exception, e: print \"Adding",
"Integer, index=True, nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is",
"the implicitly_converted_dataset_association table. \"\"\" from sqlalchemy import * from sqlalchemy.orm",
"is Implicitly_converted_table.c.ldda_parent_id except Exception, e: print \"Adding ldda_parent_id column to",
"from migrate.changeset import * import logging log = logging.getLogger( __name__",
"import * from migrate import * from migrate.changeset import *",
"Column( \"ldda_parent_id\", Integer, index=True, nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert",
"import * from sqlalchemy.orm import * from migrate import *",
"metadata.bind = migrate_engine metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata,",
"log.debug( \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\" %",
") def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() try: Implicitly_converted_table =",
"'sqlite': c = Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True,",
"Column( \"ldda_parent_id\", Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True ) else:",
"'ldda_parent_id' column to the implicitly_converted_dataset_association table. \"\"\" from sqlalchemy import",
"= migrate_engine print __doc__ metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\",",
"ForeignKey in sqlite. c = Column( \"ldda_parent_id\", Integer, index=True, nullable=True",
"sqlite. c = Column( \"ldda_parent_id\", Integer, index=True, nullable=True ) c.create(",
"% str( e ) ) def downgrade(migrate_engine): metadata.bind = migrate_engine",
"c = Column( \"ldda_parent_id\", Integer, index=True, nullable=True ) c.create( Implicitly_converted_table,",
"= logging.getLogger( __name__ ) metadata = MetaData() def upgrade(migrate_engine): metadata.bind",
"= Column( \"ldda_parent_id\", Integer, index=True, nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\")",
"e: print \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\"",
"assert c is Implicitly_converted_table.c.ldda_parent_id except Exception, e: print \"Adding ldda_parent_id",
"Integer, ForeignKey( \"library_dataset_dataset_association.id\" ), index=True, nullable=True ) else: #Can't use",
"index=True, nullable=True ) else: #Can't use the ForeignKey in sqlite.",
"%s\" % str( e ) ) def downgrade(migrate_engine): metadata.bind =",
"the ForeignKey in sqlite. c = Column( \"ldda_parent_id\", Integer, index=True,",
"str( e ) log.debug( \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table",
"e ) log.debug( \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed:",
"table failed: %s\" % str( e ) log.debug( \"Adding ldda_parent_id",
"Exception, e: print \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed:",
"sqlalchemy import * from sqlalchemy.orm import * from migrate import",
"% str( e ) log.debug( \"Dropping ldda_parent_id column from implicitly_converted_dataset_association",
"* import logging log = logging.getLogger( __name__ ) metadata =",
"migrate_engine metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True )",
"try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except",
"print __doc__ metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True",
"c is Implicitly_converted_table.c.ldda_parent_id except Exception, e: print \"Adding ldda_parent_id column",
"failed: %s\" % str( e ) log.debug( \"Adding ldda_parent_id column",
"\"implicitly_converted_dataset_association\", metadata, autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print \"Dropping",
") if migrate_engine.name != 'sqlite': c = Column( \"ldda_parent_id\", Integer,",
"ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\" % str( e",
"implicitly_converted_dataset_association table failed: %s\" % str( e ) log.debug( \"Adding",
"ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\" % str( e",
"implicitly_converted_dataset_association table failed: %s\" % str( e ) ) def",
"e ) log.debug( \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed:",
"= Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) if migrate_engine.name != 'sqlite':",
"import logging log = logging.getLogger( __name__ ) metadata = MetaData()",
"script to add 'ldda_parent_id' column to the implicitly_converted_dataset_association table. \"\"\"",
"Exception, e: print \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed:",
"Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) if migrate_engine.name !=",
"\"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\" % str(",
"\"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\" % str(",
"log = logging.getLogger( __name__ ) metadata = MetaData() def upgrade(migrate_engine):",
"), index=True, nullable=True ) else: #Can't use the ForeignKey in",
"metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) if",
"autoload=True ) Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print \"Dropping ldda_parent_id column",
"logging.getLogger( __name__ ) metadata = MetaData() def upgrade(migrate_engine): metadata.bind =",
"table. \"\"\" from sqlalchemy import * from sqlalchemy.orm import *",
"else: #Can't use the ForeignKey in sqlite. c = Column(",
"use the ForeignKey in sqlite. c = Column( \"ldda_parent_id\", Integer,",
"def downgrade(migrate_engine): metadata.bind = migrate_engine metadata.reflect() try: Implicitly_converted_table = Table(",
"autoload=True ) if migrate_engine.name != 'sqlite': c = Column( \"ldda_parent_id\",",
"__doc__ metadata.reflect() try: Implicitly_converted_table = Table( \"implicitly_converted_dataset_association\", metadata, autoload=True )",
"Table( \"implicitly_converted_dataset_association\", metadata, autoload=True ) if migrate_engine.name != 'sqlite': c",
"c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id except Exception, e:",
") metadata = MetaData() def upgrade(migrate_engine): metadata.bind = migrate_engine print",
"in sqlite. c = Column( \"ldda_parent_id\", Integer, index=True, nullable=True )",
"print \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\" %",
"migrate import * from migrate.changeset import * import logging log",
"to implicitly_converted_dataset_association table failed: %s\" % str( e ) )",
"Implicitly_converted_table.c.ldda_parent_id.drop() except Exception, e: print \"Dropping ldda_parent_id column from implicitly_converted_dataset_association",
"except Exception, e: print \"Adding ldda_parent_id column to implicitly_converted_dataset_association table",
"Implicitly_converted_table.c.ldda_parent_id except Exception, e: print \"Adding ldda_parent_id column to implicitly_converted_dataset_association",
"to add 'ldda_parent_id' column to the implicitly_converted_dataset_association table. \"\"\" from",
"migrate.changeset import * import logging log = logging.getLogger( __name__ )",
"from sqlalchemy.orm import * from migrate import * from migrate.changeset",
"nullable=True ) c.create( Implicitly_converted_table, index_name=\"ix_implicitly_converted_dataset_assoc_ldda_parent_id\") assert c is Implicitly_converted_table.c.ldda_parent_id except",
"to implicitly_converted_dataset_association table failed: %s\" % str( e ) log.debug(",
"table failed: %s\" % str( e ) log.debug( \"Dropping ldda_parent_id",
"column to the implicitly_converted_dataset_association table. \"\"\" from sqlalchemy import *",
"\"\"\" Migration script to add 'ldda_parent_id' column to the implicitly_converted_dataset_association",
"* from migrate.changeset import * import logging log = logging.getLogger(",
") log.debug( \"Dropping ldda_parent_id column from implicitly_converted_dataset_association table failed: %s\"",
"from migrate import * from migrate.changeset import * import logging",
"failed: %s\" % str( e ) log.debug( \"Dropping ldda_parent_id column",
"from implicitly_converted_dataset_association table failed: %s\" % str( e ) log.debug(",
"from sqlalchemy import * from sqlalchemy.orm import * from migrate",
"%s\" % str( e ) log.debug( \"Dropping ldda_parent_id column from",
") log.debug( \"Adding ldda_parent_id column to implicitly_converted_dataset_association table failed: %s\""
] |
[
"'#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2: '#F08E39', 3:",
"import pandas as pd import numpy as np import matplotlib.pyplot",
"X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth = df_to_mat(df) X =",
"X_con.shape[1])) print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1]))",
"R Codes/Figure_6/cMCA_ESS2018_LABCON_org.py import pandas as pd import numpy as np",
"fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth) X_con, X_lab,",
"'#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP':",
"df[key].fillna(99) def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] ==",
"'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6',",
"2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and export",
"df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha = r'$ \\alpha $' tableau10 =",
"import numpy as np import matplotlib.pyplot as plt import prince",
"CON, \" + str(alpha) + \": 1.5)\") plt.show() f_6.savefig(\"cMCA_ESS2018_labcon_org.pdf\", bbox_inches='tight')",
"'#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2:",
"value ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1])) print(\"missing value",
"X_gre.shape[1])) print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1]))",
"np import matplotlib.pyplot as plt import prince from sklearn import",
"Codes/Figure_6/cMCA_ESS2018_LABCON_org.py import pandas as pd import numpy as np import",
"= X[X[\"prtclcgb\"] == 3] X_snp = X[X[\"prtclcgb\"] == 4] X_gre",
"import itertools from cmca import CMCA from ccmca import CCMCA",
"'#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' } def fillna_based_on_dtype(df): for key",
"label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]]",
"* X_con.shape[1])) print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] *",
"cmca import CMCA from ccmca import CCMCA from matplotlib import",
"= cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:,",
"6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC',",
"5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and export plots cmca =",
"scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg: CON, \"",
"X_ldp = X[X[\"prtclcgb\"] == 3] X_snp = X[X[\"prtclcgb\"] == 4]",
"X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1])) print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum()",
"fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth)",
"and R Codes/Figure_6/cMCA_ESS2018_LABCON_org.py import pandas as pd import numpy as",
"np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5])",
"X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre)",
"as pd import numpy as np import matplotlib.pyplot as plt",
"df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] == 1] X_lab",
"Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1],",
"'#5BA053', 0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9:",
"##Disctionay for Level and Party party = {1:\"Con\", 2:\"Lab\", 3:\"LD\",",
"'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460',",
"shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg: CON,",
"X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1])) print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum()",
"from ccmca import CCMCA from matplotlib import rc plt.style.use('ggplot') df",
"prince from sklearn import utils from sklearn.cluster import DBSCAN import",
"'DPJ': '#F08E39' } def fillna_based_on_dtype(df): for key in dict(df.dtypes).keys(): if",
"1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]],",
"plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0],",
"as np import matplotlib.pyplot as plt import prince from sklearn",
"pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape,",
"* X_snp.shape[1])) print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] *",
"labels = [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8)",
"plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels",
"[handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\", shadow=False, scatterpoints=1,",
"np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 =",
"8, 10:8, 11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5},",
"== 5] X_uip = X[X[\"prtclcgb\"] == 6] X_oth = X[X[\"prtclcgb\"]",
"CMCA from ccmca import CCMCA from matplotlib import rc plt.style.use('ggplot')",
"X_gre, X_uip, X_oth = df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp,",
"= plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1],",
"'#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' }",
"= X[X[\"prtclcgb\"] == 6] X_oth = X[X[\"prtclcgb\"] == 7] print(\"missing",
"99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' } def fillna_based_on_dtype(df): for",
"print(\"missing value ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1])) print(\"missing",
"df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha",
"X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape,",
"plots cmca = CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)],",
"X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level and Party",
"X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1])) print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum()",
"'#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow':",
"'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC',",
"plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]],",
"'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1',",
"(UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1])) print(\"missing value ratio (OTH)\",",
"== np.object: df[key] = df[key].fillna('na') else: df[key] = df[key].fillna(99) def",
"df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha = r'$ \\alpha",
"X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab,",
"7:\"Other\"} ##Fitting cMCA and export plots cmca = CMCA(n_components=2, copy=True,",
"= df[key].fillna(99) def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"]",
"(X_snp.shape[0] * X_snp.shape[1])) print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0]",
"X_oth = X[X[\"prtclcgb\"] == 7] print(\"missing value ratio (CON)\", X_con.isna().sum().sum()",
"'#F08E39', 3: '#DF585C', 4: '#5BA053', 0: '#78B7B2', 6: '#ECC854', 5:",
"<reponame>tzuliu/Contrastive-Multiple-Correspondence-Analysis-cMCA<filename>Replication Python and R Codes/Figure_6/cMCA_ESS2018_LABCON_org.py import pandas as pd import",
"0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:,",
"X_gre = X[X[\"prtclcgb\"] == 5] X_uip = X[X[\"prtclcgb\"] == 6]",
"Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info()",
"for key in dict(df.dtypes).keys(): if df.dtypes[key] == np.object: df[key] =",
"plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8, 11:8,",
"'#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7:",
"X[X[\"prtclcgb\"] == 6] X_oth = X[X[\"prtclcgb\"] == 7] print(\"missing value",
"= df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] == 1] X_lab = X[X[\"prtclcgb\"]",
"X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape,",
"matplotlib.pyplot as plt import prince from sklearn import utils from",
"DBSCAN import itertools from cmca import CMCA from ccmca import",
"'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2: '#F08E39', 3: '#DF585C',",
"3: '#DF585C', 4: '#5BA053', 0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1',",
"return(X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth) X_con, X_lab, X_ldp,",
"cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg =",
"r'$ \\alpha $' tableau10 = { 'teal': '#78B7B2', 'blue': '#507AA6',",
"11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7:",
"pd import numpy as np import matplotlib.pyplot as plt import",
"X[X[\"prtclcgb\"] == 7] print(\"missing value ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0]",
"np.object: df[key] = df[key].fillna('na') else: df[key] = df[key].fillna(99) def df_to_mat(df):",
"linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles,",
"inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha = r'$",
"X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1])) print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum()",
"handles = [handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\",",
"= { 'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C',",
"/ (X_snp.shape[0] * X_snp.shape[1])) print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum() /",
"/ (X_gre.shape[0] * X_gre.shape[1])) print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum() /",
"= X[X[\"prtclcgb\"] == 7] print(\"missing value ratio (CON)\", X_con.isna().sum().sum() /",
"value ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1])) print(\"missing value",
"check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg",
"6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha = r'$ \\alpha $'",
"(X_gre.shape[0] * X_gre.shape[1])) print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0]",
"party = {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting",
"(X_con.shape[0] * X_con.shape[1])) print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0]",
"X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level and Party party =",
"import CMCA from ccmca import CCMCA from matplotlib import rc",
"bg: CON, \" + str(alpha) + \": 1.5)\") plt.show() f_6.savefig(\"cMCA_ESS2018_labcon_org.pdf\",",
"alpha = r'$ \\alpha $' tableau10 = { 'teal': '#78B7B2',",
"CCMCA from matplotlib import rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5:",
"15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8:",
"cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0],",
"== 1] X_lab = X[X[\"prtclcgb\"] == 2] X_ldp = X[X[\"prtclcgb\"]",
"'#F08E39' } def fillna_based_on_dtype(df): for key in dict(df.dtypes).keys(): if df.dtypes[key]",
"X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level",
"axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5,",
"X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth) X_con, X_lab, X_ldp, X_snp,",
"ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1])) print(\"missing value ratio",
"(X_uip.shape[0] * X_uip.shape[1])) print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0]",
"dict(df.dtypes).keys(): if df.dtypes[key] == np.object: df[key] = df[key].fillna('na') else: df[key]",
"'#507AA6', 'DPJ': '#F08E39' } def fillna_based_on_dtype(df): for key in dict(df.dtypes).keys():",
"value ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1])) print(\"missing value",
"alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0)",
"= X[X[\"prtclcgb\"] == 5] X_uip = X[X[\"prtclcgb\"] == 6] X_oth",
"plt import prince from sklearn import utils from sklearn.cluster import",
"= np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6",
"value ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab)",
"copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)]))",
"bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col =",
"1] X_lab = X[X[\"prtclcgb\"] == 2] X_ldp = X[X[\"prtclcgb\"] ==",
"6] X_oth = X[X[\"prtclcgb\"] == 7] print(\"missing value ratio (CON)\",",
"plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]],",
"X[X[\"prtclcgb\"] == 3] X_snp = X[X[\"prtclcgb\"] == 4] X_gre =",
"2: '#F08E39', 3: '#DF585C', 4: '#5BA053', 0: '#78B7B2', 6: '#ECC854',",
"and Party party = {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\",",
"X_snp.shape[1])) print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1]))",
"ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1])) print(\"missing value ratio",
"(X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth)",
"= [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1')",
"f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:,",
"* X_uip.shape[1])) print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] *",
"print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing",
"Level and Party party = {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\",",
"plt.legend(handles, labels, loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA",
"Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col'))",
"3] X_snp = X[X[\"prtclcgb\"] == 4] X_gre = X[X[\"prtclcgb\"] ==",
"matplotlib import rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9:",
"fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp,",
"X_oth.shape, X.shape) ##Disctionay for Level and Party party = {1:\"Con\",",
"fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg: CON, \" +",
"ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1])) print(\"missing value ratio",
"plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower",
"== 4] X_gre = X[X[\"prtclcgb\"] == 5] X_uip = X[X[\"prtclcgb\"]",
"ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1])) print(\"missing value ratio",
"10:8, 11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True)",
"df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] == 1] X_lab = X[X[\"prtclcgb\"] ==",
"(X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0]",
"X_ldp, X_snp, X_gre, X_uip, X_oth) X_con, X_lab, X_ldp, X_snp, X_gre,",
"= pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape,",
"'#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray':",
"X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level and",
"X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1])) print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum()",
"/ (X_con.shape[0] * X_con.shape[1])) print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum() /",
"print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con)",
"import prince from sklearn import utils from sklearn.cluster import DBSCAN",
"itertools from cmca import CMCA from ccmca import CCMCA from",
"7] print(\"missing value ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1]))",
"X_uip, X_oth = df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp, X_snp,",
"in dict(df.dtypes).keys(): if df.dtypes[key] == np.object: df[key] = df[key].fillna('na') else:",
"2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:,",
"'#507AA6', 2: '#F08E39', 3: '#DF585C', 4: '#5BA053', 0: '#78B7B2', 6:",
"$' tableau10 = { 'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39',",
"plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg: CON, \" + str(alpha) +",
"= plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles, labels,",
"{ 'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green':",
"labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles,",
"'#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' } def fillna_based_on_dtype(df):",
"(OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp)",
"import CCMCA from matplotlib import rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\")",
"0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels =",
"inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True)",
"'#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink':",
"df.dtypes[key] == np.object: df[key] = df[key].fillna('na') else: df[key] = df[key].fillna(99)",
"print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1])) print(\"missing",
"= np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5,",
"ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1])) print(\"missing value ratio",
"df[key] = df[key].fillna('na') else: df[key] = df[key].fillna(99) def df_to_mat(df): X",
"= df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip,",
"X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape,",
"X_snp = X[X[\"prtclcgb\"] == 4] X_gre = X[X[\"prtclcgb\"] == 5]",
"X_lab = X[X[\"prtclcgb\"] == 2] X_ldp = X[X[\"prtclcgb\"] == 3]",
"12:8, 13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6},",
"X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for Level and Party party",
"c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles =",
"df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8, 11:8, 12:8,",
"df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth])",
"from matplotlib import rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8,",
"/ (X_lab.shape[0] * X_lab.shape[1])) print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum() /",
"tableau10 = { 'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red':",
"X_uip = X[X[\"prtclcgb\"] == 6] X_oth = X[X[\"prtclcgb\"] == 7]",
"5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha =",
"fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp, X_gre, X_uip,",
"X_uip, X_oth) X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth =",
"X_lab.shape[1])) print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1]))",
"= np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info",
"label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3,",
"value ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value",
"and export plots cmca = CMCA(n_components=2, copy=True, check_input=True) cmca =",
"X[X[\"prtclcgb\"] == 1] X_lab = X[X[\"prtclcgb\"] == 2] X_ldp =",
"'#DF585C', 4: '#5BA053', 0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8:",
"X_uip.shape[1])) print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1]))",
"} def fillna_based_on_dtype(df): for key in dict(df.dtypes).keys(): if df.dtypes[key] ==",
"'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460',",
"ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value ratio",
"X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay",
"'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2: '#F08E39',",
"loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB,",
"cMCA and export plots cmca = CMCA(n_components=2, copy=True, check_input=True) cmca",
"'#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown':",
"5] X_uip = X[X[\"prtclcgb\"] == 6] X_oth = X[X[\"prtclcgb\"] ==",
"X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum()",
"'#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1:",
"X_snp, X_gre, X_uip, X_oth = df_to_mat(df) X = pd.concat([X_con, X_lab,",
"df[key] = df[key].fillna(99) def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con =",
"X_oth) X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth = df_to_mat(df)",
"from sklearn import utils from sklearn.cluster import DBSCAN import itertools",
"(tg: LAB, bg: CON, \" + str(alpha) + \": 1.5)\")",
"pandas as pd import numpy as np import matplotlib.pyplot as",
"/ (X_uip.shape[0] * X_uip.shape[1])) print(\"missing value ratio (OTH)\", X_oth.isna().sum().sum() /",
"== 6] X_oth = X[X[\"prtclcgb\"] == 7] print(\"missing value ratio",
"if df.dtypes[key] == np.object: df[key] = df[key].fillna('na') else: df[key] =",
"7}, inplace=True) alpha = r'$ \\alpha $' tableau10 = {",
"= X[X[\"prtclcgb\"] == 2] X_ldp = X[X[\"prtclcgb\"] == 3] X_snp",
"X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] == 1] X_lab =",
"= [handles[1],handles[0]] labels = [\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\", shadow=False,",
"def fillna_based_on_dtype(df): for key in dict(df.dtypes).keys(): if df.dtypes[key] == np.object:",
"2.5]) plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3,",
"from cmca import CMCA from ccmca import CCMCA from matplotlib",
"(CON)\", X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1])) print(\"missing value ratio (LAB)\",",
"9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39'",
"X[X[\"prtclcgb\"] == 5] X_uip = X[X[\"prtclcgb\"] == 6] X_oth =",
"'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854',",
"X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape)",
"2] X_ldp = X[X[\"prtclcgb\"] == 3] X_snp = X[X[\"prtclcgb\"] ==",
"1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles",
"import DBSCAN import itertools from cmca import CMCA from ccmca",
"3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and export plots",
"cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col",
"fillna_based_on_dtype(df): for key in dict(df.dtypes).keys(): if df.dtypes[key] == np.object: df[key]",
"(LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1])) print(\"missing value ratio (LDP)\",",
"4] X_gre = X[X[\"prtclcgb\"] == 5] X_uip = X[X[\"prtclcgb\"] ==",
"as plt import prince from sklearn import utils from sklearn.cluster",
"X = pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape,",
"def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con = X[X[\"prtclcgb\"] == 1]",
"(X_lab.shape[0] * X_lab.shape[1])) print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0]",
"* X_ldp.shape[1])) print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] *",
"rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8,",
"0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC',",
"'#ECC854', 5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99:",
"8, 9: 8, 10:8, 11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True)",
"X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth = df_to_mat(df) X",
"plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg: CON, \" + str(alpha)",
"inplace=True) alpha = r'$ \\alpha $' tableau10 = { 'teal':",
"linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels =",
"print(\"missing value ratio (LAB)\", X_lab.isna().sum().sum() / (X_lab.shape[0] * X_lab.shape[1])) print(\"missing",
"fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp, X_gre,",
"np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info =",
"fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth) X_con,",
"{1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and",
"* X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con,",
"/ (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum() /",
"4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and export plots cmca",
"= X[X[\"prtclcgb\"] == 1] X_lab = X[X[\"prtclcgb\"] == 2] X_ldp",
"= cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)]))",
"4: '#5BA053', 0: '#78B7B2', 6: '#ECC854', 5: '#AF7BA1', 8: '#FD9EA9',",
"export plots cmca = CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)],",
"= pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8, 11:8, 12:8, 13:8,",
"alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels",
"X[X[\"prtclcgb\"] == 4] X_gre = X[X[\"prtclcgb\"] == 5] X_uip =",
"df[key].fillna('na') else: df[key] = df[key].fillna(99) def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]]",
"'#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053', 'purple':",
"ccmca import CCMCA from matplotlib import rc plt.style.use('ggplot') df =",
"X_ldp, X_snp, X_gre, X_uip, X_oth]) print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape,",
"[\"Con\",\"Lab\"] plt.legend(handles, labels, loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2')",
"key in dict(df.dtypes).keys(): if df.dtypes[key] == np.object: df[key] = df[key].fillna('na')",
"handles, labels = plt.gca().get_legend_handles_labels() handles = [handles[1],handles[0]] labels = [\"Con\",\"Lab\"]",
"CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg =",
"X_oth = df_to_mat(df) X = pd.concat([X_con, X_lab, X_ldp, X_snp, X_gre,",
"labels, loc=\"lower right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg:",
"(GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1])) print(\"missing value ratio (UIP)\",",
"== 3] X_snp = X[X[\"prtclcgb\"] == 4] X_gre = X[X[\"prtclcgb\"]",
"X_ldp.shape[1])) print(\"missing value ratio (SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1]))",
"'#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9', 'gray': '#BAB0AC', 7: '#9A7460', 1:",
"X_gre, X_uip, X_oth) X_con, X_lab, X_ldp, X_snp, X_gre, X_uip, X_oth",
"Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) handles, labels = plt.gca().get_legend_handles_labels()",
"* X_lab.shape[1])) print(\"missing value ratio (LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] *",
"ratio (OTH)\", X_oth.isna().sum().sum() / (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp)",
"import rc plt.style.use('ggplot') df = pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8,",
"inplace=True) df[\"prtclcgb\"].replace({8: 7}, inplace=True) alpha = r'$ \\alpha $' tableau10",
"'teal': '#78B7B2', 'blue': '#507AA6', 'orange': '#F08E39', 'red': '#DF585C', 'green': '#5BA053',",
"value ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1])) print(\"missing value",
"'#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ':",
"Party party = {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"}",
"from sklearn.cluster import DBSCAN import itertools from cmca import CMCA",
"Python and R Codes/Figure_6/cMCA_ESS2018_LABCON_org.py import pandas as pd import numpy",
"sklearn.cluster import DBSCAN import itertools from cmca import CMCA from",
"-1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6', 'DPJ': '#F08E39' } def",
"9: 8, 10:8, 11:8, 12:8, 13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6:",
"/ (X_oth.shape[0] * X_oth.shape[1])) fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip)",
"5: '#AF7BA1', 8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC',",
"import utils from sklearn.cluster import DBSCAN import itertools from cmca",
"= df[key].fillna('na') else: df[key] = df[key].fillna(99) def df_to_mat(df): X =",
"df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8, 11:8, 12:8, 13:8, 15:8, 19:8},",
"sklearn import utils from sklearn.cluster import DBSCAN import itertools from",
"* X_gre.shape[1])) print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] *",
"value ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0] * X_con.shape[1])) print(\"missing value",
"'#9A7460', 1: '#507AA6', 2: '#F08E39', 3: '#DF585C', 4: '#5BA053', 0:",
"right\", shadow=False, scatterpoints=1, fontsize=8) plt.xlabel('cPC1') plt.ylabel('cPC2') plt.title(\"cMCA (tg: LAB, bg:",
"19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True) df[\"prtclcgb\"].replace({8: 7},",
"(LDP)\", X_ldp.isna().sum().sum() / (X_ldp.shape[0] * X_ldp.shape[1])) print(\"missing value ratio (SNP)\",",
"for Level and Party party = {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\",",
"X_ldp, X_snp, X_gre, X_uip, X_oth = df_to_mat(df) X = pd.concat([X_con,",
"7: '#9A7460', 1: '#507AA6', 2: '#F08E39', 3: '#DF585C', 4: '#5BA053',",
"print(\"missing value ratio (GRE)\", X_gre.isna().sum().sum() / (X_gre.shape[0] * X_gre.shape[1])) print(\"missing",
"cmca = CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5)",
"6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA and export plots cmca = CMCA(n_components=2,",
"13:8, 15:8, 19:8}, inplace=True) df[\"prtclcgb\"].replace({6: 5}, inplace=True) df[\"prtclcgb\"].replace({7: 6}, inplace=True)",
"X[X[\"prtclcgb\"] == 2] X_ldp = X[X[\"prtclcgb\"] == 3] X_snp =",
"== 7] print(\"missing value ratio (CON)\", X_con.isna().sum().sum() / (X_con.shape[0] *",
"1: '#507AA6', 2: '#F08E39', 3: '#DF585C', 4: '#5BA053', 0: '#78B7B2',",
"plt.title(\"cMCA (tg: LAB, bg: CON, \" + str(alpha) + \":",
"= X[X[\"prtclcgb\"] == 4] X_gre = X[X[\"prtclcgb\"] == 5] X_uip",
"plt.ylim([-2.5, 2.5]) plt.scatter(Y_fg[:, 0], Y_fg[:, 1], c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0)",
"alpha=1.5) Y_fg = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)])) Y_bg = np.array(cmca.transform(X_con.iloc[:,0:(X.shape[1]-3)])) Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)],",
"= CMCA(n_components=2, copy=True, check_input=True) cmca = cmca.fit(fg=X_lab.iloc[:,0:(X_lab.shape[1]-3)], bg=X_con.iloc[:,0:(X_con.shape[1]-3)], alpha=1.5) Y_fg",
"fillna_based_on_dtype(X_con) fillna_based_on_dtype(X_lab) fillna_based_on_dtype(X_ldp) fillna_based_on_dtype(X_snp) fillna_based_on_dtype(X_gre) fillna_based_on_dtype(X_uip) fillna_based_on_dtype(X_oth) return(X_con, X_lab, X_ldp,",
"import matplotlib.pyplot as plt import prince from sklearn import utils",
"= {1:\"Con\", 2:\"Lab\", 3:\"LD\", 4:\"SNP\", 5:\"Green\", 6:\"UKIP\", 7:\"Other\"} ##Fitting cMCA",
"prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure() plt.xlim([-2.5, 2.5]) plt.ylim([-2.5, 2.5])",
"'green': '#5BA053', 'purple': '#AF7BA1', 'yellow': '#ECC854', 'brown': '#9A7460', 'pink': '#FD9EA9',",
"\\alpha $' tableau10 = { 'teal': '#78B7B2', 'blue': '#507AA6', 'orange':",
"(SNP)\", X_snp.isna().sum().sum() / (X_snp.shape[0] * X_snp.shape[1])) print(\"missing value ratio (GRE)\",",
"numpy as np import matplotlib.pyplot as plt import prince from",
"print(X_con.shape, X_lab.shape, X_ldp.shape, X_snp.shape, X_gre.shape, X_uip.shape, X_oth.shape, X.shape) ##Disctionay for",
"X_snp, X_gre, X_uip, X_oth) X_con, X_lab, X_ldp, X_snp, X_gre, X_uip,",
"c=tableau10[X_lab[\"prtclcgb\"].iloc[0]], label=party[X_lab[\"prtclcgb\"].iloc[0]], alpha=0.3, linewidths=0) plt.scatter(Y_bg[:, 0], Y_bg[:, 1], c=tableau10[X_con[\"prtclcgb\"].iloc[0]], label=party[X_con[\"prtclcgb\"].iloc[0]],",
"'#BAB0AC', 7: '#9A7460', 1: '#507AA6', 2: '#F08E39', 3: '#DF585C', 4:",
"utils from sklearn.cluster import DBSCAN import itertools from cmca import",
"else: df[key] = df[key].fillna(99) def df_to_mat(df): X = df.iloc[:,np.r_[1:(df.shape[1])]] X_con",
"X_con = X[X[\"prtclcgb\"] == 1] X_lab = X[X[\"prtclcgb\"] == 2]",
"LAB, bg: CON, \" + str(alpha) + \": 1.5)\") plt.show()",
"= r'$ \\alpha $' tableau10 = { 'teal': '#78B7B2', 'blue':",
"'LDP': '#507AA6', 'DPJ': '#F08E39' } def fillna_based_on_dtype(df): for key in",
"pd.read_csv(\"./uk2018.csv\") df[\"prtclcgb\"].replace({5: 8, 9: 8, 10:8, 11:8, 12:8, 13:8, 15:8,",
"X.shape) ##Disctionay for Level and Party party = {1:\"Con\", 2:\"Lab\",",
"== 2] X_ldp = X[X[\"prtclcgb\"] == 3] X_snp = X[X[\"prtclcgb\"]",
"print(\"missing value ratio (UIP)\", X_uip.isna().sum().sum() / (X_uip.shape[0] * X_uip.shape[1])) print(\"missing",
"##Fitting cMCA and export plots cmca = CMCA(n_components=2, copy=True, check_input=True)",
"8: '#FD9EA9', 9: '#BAB0AC', -1: '#BAB0AC', 99: '#BAB0AC', 'LDP': '#507AA6',",
"Y_fg_col = np.array(cmca.transform(X_lab.iloc[:,0:(X.shape[1]-3)], axis='col')) prefix_to_info = cmca.gen_prefix_to_info() f_6 = plt.figure()"
] |
[
"example, given [(1, 3), (5, 8), (4, 10), (20, 25)],",
"interval in intervals[1:]: curr_start, curr_end = interval if end <",
"necessarily ordered in any way. For example, given [(1, 3),",
"merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0]) merged_intervals",
"List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0]) merged_intervals = [] start =",
"new list of intervals where all overlapping intervals have been",
"merged_intervals = [] start = intervals[0][0] end = intervals[0][1] #",
"8), (4, 10), (20, 25), (6, 12)])) \"\"\" SPECS: TIME",
"int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0]) merged_intervals = []",
"= intervals[0][0] end = intervals[0][1] # generating the merged intervals",
"way. For example, given [(1, 3), (5, 8), (4, 10),",
"merged_intervals.append((start, end)) return merged_intervals if __name__ == \"__main__\": print(merge_intervals([(1, 3),",
"(20, 25)], you should return [(1, 3), (4, 10), (20,",
"(5, 8), (4, 10), (20, 25)])) print(merge_intervals([(1, 3), (5, 8),",
"= [] start = intervals[0][0] end = intervals[0][1] # generating",
"in any way. For example, given [(1, 3), (5, 8),",
"3), (4, 10), (20, 25)]. \"\"\" from typing import List,",
"end = intervals[0][1] # generating the merged intervals for interval",
"intervals[0][1] # generating the merged intervals for interval in intervals[1:]:",
"intervals[0][0] end = intervals[0][1] # generating the merged intervals for",
"input list is not necessarily ordered in any way. For",
"\"\"\" from typing import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]])",
"print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25), (6, 12)]))",
"return a new list of intervals where all overlapping intervals",
"start = curr_start end = curr_end elif end < curr_end",
"overlapping intervals have been merged. The input list is not",
"3), (5, 8), (4, 10), (20, 25)])) print(merge_intervals([(1, 3), (5,",
"end)) start = curr_start end = curr_end elif end <",
"interval merged_intervals.append((start, end)) return merged_intervals if __name__ == \"__main__\": print(merge_intervals([(1,",
"The input list is not necessarily ordered in any way.",
"return [(1, 3), (4, 10), (20, 25)]. \"\"\" from typing",
"from typing import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) ->",
"last interval merged_intervals.append((start, end)) return merged_intervals if __name__ == \"__main__\":",
"end = curr_end # adding the last interval merged_intervals.append((start, end))",
"list of intervals where all overlapping intervals have been merged.",
"x: x[0]) merged_intervals = [] start = intervals[0][0] end =",
"import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]:",
"x[0]) merged_intervals = [] start = intervals[0][0] end = intervals[0][1]",
"(4, 10), (20, 25)], you should return [(1, 3), (4,",
"if __name__ == \"__main__\": print(merge_intervals([(1, 3), (5, 8), (4, 10),",
"end < curr_end and end > curr_start: end = curr_end",
"10), (20, 25), (6, 12)])) \"\"\" SPECS: TIME COMPLEXITY: O(n)",
"curr_end and end > curr_start: end = curr_end # adding",
"have been merged. The input list is not necessarily ordered",
"print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25)])) print(merge_intervals([(1, 3),",
"curr_end = interval if end < curr_start: merged_intervals.append((start, end)) start",
"in intervals[1:]: curr_start, curr_end = interval if end < curr_start:",
"10), (20, 25)])) print(merge_intervals([(1, 3), (5, 8), (4, 10), (20,",
"curr_start: merged_intervals.append((start, end)) start = curr_start end = curr_end elif",
"end > curr_start: end = curr_end # adding the last",
"intervals[1:]: curr_start, curr_end = interval if end < curr_start: merged_intervals.append((start,",
"> curr_start: end = curr_end # adding the last interval",
"25), (6, 12)])) \"\"\" SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY:",
"end < curr_start: merged_intervals.append((start, end)) start = curr_start end =",
"8), (4, 10), (20, 25)])) print(merge_intervals([(1, 3), (5, 8), (4,",
"intervals for interval in intervals[1:]: curr_start, curr_end = interval if",
"# generating the merged intervals for interval in intervals[1:]: curr_start,",
"curr_end # adding the last interval merged_intervals.append((start, end)) return merged_intervals",
"(5, 8), (4, 10), (20, 25), (6, 12)])) \"\"\" SPECS:",
"the last interval merged_intervals.append((start, end)) return merged_intervals if __name__ ==",
"ordered in any way. For example, given [(1, 3), (5,",
"adding the last interval merged_intervals.append((start, end)) return merged_intervals if __name__",
"of possibly overlapping intervals, return a new list of intervals",
"__name__ == \"__main__\": print(merge_intervals([(1, 3), (5, 8), (4, 10), (20,",
"intervals.sort(key=lambda x: x[0]) merged_intervals = [] start = intervals[0][0] end",
"3), (5, 8), (4, 10), (20, 25), (6, 12)])) \"\"\"",
"merged_intervals.append((start, end)) start = curr_start end = curr_end elif end",
"\"__main__\": print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25)])) print(merge_intervals([(1,",
"Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda x:",
"<gh_stars>10-100 \"\"\" Problem: Given a list of possibly overlapping intervals,",
"all overlapping intervals have been merged. The input list is",
"list is not necessarily ordered in any way. For example,",
"# adding the last interval merged_intervals.append((start, end)) return merged_intervals if",
"12)])) \"\"\" SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(n) \"\"\"",
"[(1, 3), (4, 10), (20, 25)]. \"\"\" from typing import",
"should return [(1, 3), (4, 10), (20, 25)]. \"\"\" from",
"= curr_end # adding the last interval merged_intervals.append((start, end)) return",
"List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda",
"start = intervals[0][0] end = intervals[0][1] # generating the merged",
"a list of possibly overlapping intervals, return a new list",
"any way. For example, given [(1, 3), (5, 8), (4,",
"for interval in intervals[1:]: curr_start, curr_end = interval if end",
"(6, 12)])) \"\"\" SPECS: TIME COMPLEXITY: O(n) SPACE COMPLEXITY: O(n)",
"[(1, 3), (5, 8), (4, 10), (20, 25)], you should",
"< curr_start: merged_intervals.append((start, end)) start = curr_start end = curr_end",
"interval if end < curr_start: merged_intervals.append((start, end)) start = curr_start",
"return merged_intervals if __name__ == \"__main__\": print(merge_intervals([(1, 3), (5, 8),",
"been merged. The input list is not necessarily ordered in",
"25)]. \"\"\" from typing import List, Tuple def merge_intervals(intervals: List[Tuple[int,",
"end)) return merged_intervals if __name__ == \"__main__\": print(merge_intervals([(1, 3), (5,",
"curr_start end = curr_end elif end < curr_end and end",
"= curr_start end = curr_end elif end < curr_end and",
"possibly overlapping intervals, return a new list of intervals where",
"= curr_end elif end < curr_end and end > curr_start:",
"\"\"\" Problem: Given a list of possibly overlapping intervals, return",
"10), (20, 25)], you should return [(1, 3), (4, 10),",
"not necessarily ordered in any way. For example, given [(1,",
"(4, 10), (20, 25)])) print(merge_intervals([(1, 3), (5, 8), (4, 10),",
"(20, 25)]. \"\"\" from typing import List, Tuple def merge_intervals(intervals:",
"For example, given [(1, 3), (5, 8), (4, 10), (20,",
"is not necessarily ordered in any way. For example, given",
"25)])) print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25), (6,",
"overlapping intervals, return a new list of intervals where all",
"3), (5, 8), (4, 10), (20, 25)], you should return",
"(20, 25), (6, 12)])) \"\"\" SPECS: TIME COMPLEXITY: O(n) SPACE",
"merged. The input list is not necessarily ordered in any",
"(20, 25)])) print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25),",
"merged_intervals if __name__ == \"__main__\": print(merge_intervals([(1, 3), (5, 8), (4,",
"end = curr_end elif end < curr_end and end >",
"of intervals where all overlapping intervals have been merged. The",
"intervals where all overlapping intervals have been merged. The input",
"= interval if end < curr_start: merged_intervals.append((start, end)) start =",
"Problem: Given a list of possibly overlapping intervals, return a",
"intervals, return a new list of intervals where all overlapping",
"typing import List, Tuple def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int,",
"def merge_intervals(intervals: List[Tuple[int, int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0])",
"the merged intervals for interval in intervals[1:]: curr_start, curr_end =",
"-> List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0]) merged_intervals = [] start",
"merged intervals for interval in intervals[1:]: curr_start, curr_end = interval",
"(5, 8), (4, 10), (20, 25)], you should return [(1,",
"< curr_end and end > curr_start: end = curr_end #",
"List[Tuple[int, int]]) -> List[Tuple[int, int]]: intervals.sort(key=lambda x: x[0]) merged_intervals =",
"[] start = intervals[0][0] end = intervals[0][1] # generating the",
"Given a list of possibly overlapping intervals, return a new",
"if end < curr_start: merged_intervals.append((start, end)) start = curr_start end",
"(4, 10), (20, 25)]. \"\"\" from typing import List, Tuple",
"elif end < curr_end and end > curr_start: end =",
"where all overlapping intervals have been merged. The input list",
"given [(1, 3), (5, 8), (4, 10), (20, 25)], you",
"int]]: intervals.sort(key=lambda x: x[0]) merged_intervals = [] start = intervals[0][0]",
"curr_start: end = curr_end # adding the last interval merged_intervals.append((start,",
"== \"__main__\": print(merge_intervals([(1, 3), (5, 8), (4, 10), (20, 25)]))",
"curr_start, curr_end = interval if end < curr_start: merged_intervals.append((start, end))",
"generating the merged intervals for interval in intervals[1:]: curr_start, curr_end",
"25)], you should return [(1, 3), (4, 10), (20, 25)].",
"a new list of intervals where all overlapping intervals have",
"8), (4, 10), (20, 25)], you should return [(1, 3),",
"curr_end elif end < curr_end and end > curr_start: end",
"10), (20, 25)]. \"\"\" from typing import List, Tuple def",
"list of possibly overlapping intervals, return a new list of",
"(4, 10), (20, 25), (6, 12)])) \"\"\" SPECS: TIME COMPLEXITY:",
"and end > curr_start: end = curr_end # adding the",
"intervals have been merged. The input list is not necessarily",
"= intervals[0][1] # generating the merged intervals for interval in",
"you should return [(1, 3), (4, 10), (20, 25)]. \"\"\""
] |
[
"Determine if the command is valid. If so, take action",
"segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There is nothing better",
"= str(\"green on\") GREENOFF = str(\"green off\") YELLOWON = str(\"yellow",
"elif command.find(GREENOFF) >= 0: GPIO.output(5, False) response = emoji.emojize(\"\" +",
"segment.scramble() elif command.find(HACKER) >= 0: print('Message') response = segment.hacker() elif",
"response = segment.scramble() elif command.find(HACKER) >= 0: print('Message') response =",
":thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED Commands elif command.find(BLUEON) >=",
"0: GPIO.output(27, True) response = emoji.emojize(\"\" + \"Turning :red_circle: ON...\")",
"= emoji.emojize(\"\" + \"Turning :radio_button: OFF...\") # Red LED Commands",
"command.find(REDON) >= 0: GPIO.output(27, True) response = emoji.emojize(\"\" + \"Turning",
"elif command.find(SINGLEREADING) >= 0: a = lite.printReading() a = int(a)",
"Pin Setup GPIO.setup(17, GPIO.OUT) # BLUE LED GPIO.setup(27, GPIO.OUT) #",
":radio_button: OFF...\") # Red LED Commands elif command.find(REDON) >= 0:",
"0: GPIO.output(5, False) response = emoji.emojize(\"\" + \"Turning :green_apple: OFF...\")",
"import slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False)",
"= False # Your handling code goes in this function",
"# GREEN LED GPIO.setup(22, GPIO.OUT) # YELLOW LED GPIO.setup(12, GPIO.OUT)",
"Green LED Commands elif command.find(GREENON) >= 0: GPIO.output(5, True) response",
"better than scrambled eggs! :egg:\")) response = segment.scramble() elif command.find(HACKER)",
"str(\"yellow on\") YELLOWOFF = str(\"yellow off\") CLOCK = str(\"update clock\")",
"\"Turning :sunny: OFF...\") # 7 Segment Commands elif command.find(CLOCK) >=",
"elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There is nothing better than",
"LED GPIO.setup(22, GPIO.OUT) # YELLOW LED GPIO.setup(12, GPIO.OUT) # LDR",
"take action and return a response, if necessary. \"\"\" if",
"and return a response, if necessary. \"\"\" if not setup:",
"the 7') SINGLEREADING = str('light') def setup(): import RPi.GPIO as",
"time.sleep(1) print(a) response = ('Here is what the LDR Sensor",
"0: GPIO.output(27, False) response = emoji.emojize(\"\" + \"Turning :red_circle: OFF...\")",
"print(a) response = ('Here is what the LDR Sensor said",
"# Blue LED Commands elif command.find(BLUEON) >= 0: GPIO.output(17, True)",
"response = emoji.emojize(\"\" + \"Turning :red_circle: OFF...\") # Green LED",
"= str(\"yellow off\") CLOCK = str(\"update clock\") SCRAMBLE = str('scramble",
"\"Turning :red_circle: OFF...\") # Green LED Commands elif command.find(GREENON) >=",
"# Put your commands here COMMAND1 = \"testing testing\" COMMAND2",
"off\") CLOCK = str(\"update clock\") SCRAMBLE = str('scramble the 7')",
"command.find(HACKER) >= 0: print('Message') response = segment.hacker() elif command.find(SINGLEREADING) >=",
"than scrambled eggs! :egg:\")) response = segment.scramble() elif command.find(HACKER) >=",
":red_circle: ON...\") elif command.find(REDOFF) >= 0: GPIO.output(27, False) response =",
"scrambled eggs! :egg:\")) response = segment.scramble() elif command.find(HACKER) >= 0:",
"= str('hack the 7') SINGLEREADING = str('light') def setup(): import",
"\"roger roger\" BLUEON = str(\"blue on\") BLUEOFF = str(\"blue off\")",
"('Here is what the LDR Sensor said to me: '",
"command.find(BLUEON) >= 0: GPIO.output(17, True) response = emoji.emojize(\"\" + \"Turning",
"command.find(CLOCK) >= 0: print('Updating the clock!') response = segment.updateClock() elif",
"\"Turning :radio_button: ON...\") elif command.find(BLUEOFF) >= 0: GPIO.output(17, False) response",
"GPIO.output(27, True) response = emoji.emojize(\"\" + \"Turning :red_circle: ON...\") elif",
"command is valid. If so, take action and return a",
"command.find(GREENON) >= 0: GPIO.output(5, True) response = emoji.emojize(\"\" + \"Turning",
">= 0: GPIO.output(27, True) response = emoji.emojize(\"\" + \"Turning :red_circle:",
"emoji.emojize(\"\" + \"Turning :green_apple: OFF...\") # Yellow LED Commands elif",
"= segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There is nothing",
"your commands here COMMAND1 = \"testing testing\" COMMAND2 = \"roger",
"commands here COMMAND1 = \"testing testing\" COMMAND2 = \"roger roger\"",
"# BLUE LED GPIO.setup(27, GPIO.OUT) # RED LED GPIO.setup(5, GPIO.OUT)",
"LED Commands elif command.find(GREENON) >= 0: GPIO.output(5, True) response =",
"so, take action and return a response, if necessary. \"\"\"",
">= 0: GPIO.output(17, True) response = emoji.emojize(\"\" + \"Turning :radio_button:",
"code goes in this function def handle_command(command): \"\"\" Determine if",
"Setup GPIO.setup(17, GPIO.OUT) # BLUE LED GPIO.setup(27, GPIO.OUT) # RED",
"response = emoji.emojize(\"\" + \"Turning :green_apple: OFF...\") # Yellow LED",
"0: a = lite.printReading() a = int(a) time.sleep(1) print(a) response",
"elif command.find(BLUEON) >= 0: GPIO.output(17, True) response = emoji.emojize(\"\" +",
"Commands elif command.find(BLUEON) >= 0: GPIO.output(17, True) response = emoji.emojize(\"\"",
"str(\"blue on\") BLUEOFF = str(\"blue off\") REDON = str(\"red on\")",
"GPIO.setup(5, GPIO.OUT) # GREEN LED GPIO.setup(22, GPIO.OUT) # YELLOW LED",
"eggs! :egg:\")) response = segment.scramble() elif command.find(HACKER) >= 0: print('Message')",
"+ \"Turning :radio_button: ON...\") elif command.find(BLUEOFF) >= 0: GPIO.output(17, False)",
"Commands elif command.find(GREENON) >= 0: GPIO.output(5, True) response = emoji.emojize(\"\"",
"= segment.hacker() elif command.find(SINGLEREADING) >= 0: a = lite.printReading() a",
"is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED Commands elif command.find(BLUEON)",
"response = \"\" if command.find(COMMAND1) >= 0: response = str(\"Surprise!\")",
"as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup GPIO.setup(17, GPIO.OUT) #",
"= \"roger roger\" BLUEON = str(\"blue on\") BLUEOFF = str(\"blue",
"= emoji.emojize(\"\" + \"Turning :sunny: OFF...\") # 7 Segment Commands",
"True response = \"\" if command.find(COMMAND1) >= 0: response =",
"print('Message') response = segment.hacker() elif command.find(SINGLEREADING) >= 0: a =",
"+ \"Turning :green_apple: OFF...\") # Yellow LED Commands elif command.find(YELLOWON)",
"Your handling code goes in this function def handle_command(command): \"\"\"",
"RPi.GPIO as GPIO import slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7 as",
"GPIO.setwarnings(False) # Pin Setup GPIO.setup(17, GPIO.OUT) # BLUE LED GPIO.setup(27,",
"elif command.find(YELLOWON) >= 0: GPIO.output(22, True) response = emoji.emojize(\"\" +",
"command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response = emoji.emojize(\"\" + \"Turning",
"elif command.find(GREENON) >= 0: GPIO.output(5, True) response = emoji.emojize(\"\" +",
"emoji.emojize(\"\" + \"Turning :radio_button: OFF...\") # Red LED Commands elif",
"is nothing better than scrambled eggs! :egg:\")) response = segment.scramble()",
"emoji.emojize(\"\" + \"Turning :sunny: ON...\") elif command.find(YELLOWOFF) >= 0: GPIO.output(22,",
":egg:\")) response = segment.scramble() elif command.find(HACKER) >= 0: print('Message') response",
"\"testing testing\" COMMAND2 = \"roger roger\" BLUEON = str(\"blue on\")",
"YELLOWON = str(\"yellow on\") YELLOWOFF = str(\"yellow off\") CLOCK =",
"str(\"green on\") GREENOFF = str(\"green off\") YELLOWON = str(\"yellow on\")",
"OFF...\") # Red LED Commands elif command.find(REDON) >= 0: GPIO.output(27,",
"what the LDR Sensor said to me: ' + str(a))",
"OFF...\") # Green LED Commands elif command.find(GREENON) >= 0: GPIO.output(5,",
"response = ('Here is what the LDR Sensor said to",
"# YELLOW LED GPIO.setup(12, GPIO.OUT) # LDR setup = False",
"ON...\") elif command.find(GREENOFF) >= 0: GPIO.output(5, False) response = emoji.emojize(\"\"",
"SCRAMBLE = str('scramble the 7') HACKER = str('hack the 7')",
"0: print('Updating the clock!') response = segment.updateClock() elif command.find(SCRAMBLE) >=",
"True) response = emoji.emojize(\"\" + \"Turning :red_circle: ON...\") elif command.find(REDOFF)",
"\"\"\" Determine if the command is valid. If so, take",
">= 0: GPIO.output(17, False) response = emoji.emojize(\"\" + \"Turning :radio_button:",
"LED Commands elif command.find(REDON) >= 0: GPIO.output(27, True) response =",
">= 0: response = (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) #",
"# RED LED GPIO.setup(5, GPIO.OUT) # GREEN LED GPIO.setup(22, GPIO.OUT)",
"if necessary. \"\"\" if not setup: setup_gpio() setup = True",
"= emoji.emojize(\"\" + \"Turning :green_apple: OFF...\") # Yellow LED Commands",
"Segment Commands elif command.find(CLOCK) >= 0: print('Updating the clock!') response",
"ON...\") elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response = emoji.emojize(\"\"",
"GPIO.OUT) # YELLOW LED GPIO.setup(12, GPIO.OUT) # LDR setup =",
"import time import emoji # Put your commands here COMMAND1",
"\"\" if command.find(COMMAND1) >= 0: response = str(\"Surprise!\") elif command.find(COMMAND2)",
"LED Commands elif command.find(BLUEON) >= 0: GPIO.output(17, True) response =",
":green_apple: ON...\") elif command.find(GREENOFF) >= 0: GPIO.output(5, False) response =",
"GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup GPIO.setup(17, GPIO.OUT) # BLUE LED",
"ON...\") elif command.find(REDOFF) >= 0: GPIO.output(27, False) response = emoji.emojize(\"\"",
":radio_button: ON...\") elif command.find(BLUEOFF) >= 0: GPIO.output(17, False) response =",
"command.find(GREENOFF) >= 0: GPIO.output(5, False) response = emoji.emojize(\"\" + \"Turning",
"False) response = emoji.emojize(\"\" + \"Turning :green_apple: OFF...\") # Yellow",
"command.find(YELLOWON) >= 0: GPIO.output(22, True) response = emoji.emojize(\"\" + \"Turning",
"= str(\"red off\") GREENON = str(\"green on\") GREENOFF = str(\"green",
"elif command.find(HACKER) >= 0: print('Message') response = segment.hacker() elif command.find(SINGLEREADING)",
"str('hack the 7') SINGLEREADING = str('light') def setup(): import RPi.GPIO",
"str(\"red on\") REDOFF = str(\"red off\") GREENON = str(\"green on\")",
"REDOFF = str(\"red off\") GREENON = str(\"green on\") GREENOFF =",
"str('light') def setup(): import RPi.GPIO as GPIO import slackbot_wems.chris.light as",
"Commands elif command.find(YELLOWON) >= 0: GPIO.output(22, True) response = emoji.emojize(\"\"",
"clock!') response = segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There",
"setup = True response = \"\" if command.find(COMMAND1) >= 0:",
"GPIO import slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM)",
"a = lite.printReading() a = int(a) time.sleep(1) print(a) response =",
"elif command.find(REDOFF) >= 0: GPIO.output(27, False) response = emoji.emojize(\"\" +",
"setup = False # Your handling code goes in this",
"roger\" BLUEON = str(\"blue on\") BLUEOFF = str(\"blue off\") REDON",
"= emoji.emojize(\"\" + \"Turning :red_circle: OFF...\") # Green LED Commands",
"\"Turning :green_apple: OFF...\") # Yellow LED Commands elif command.find(YELLOWON) >=",
"= str(\"blue off\") REDON = str(\"red on\") REDOFF = str(\"red",
"LED GPIO.setup(5, GPIO.OUT) # GREEN LED GPIO.setup(22, GPIO.OUT) # YELLOW",
"action and return a response, if necessary. \"\"\" if not",
"def setup(): import RPi.GPIO as GPIO import slackbot_wems.chris.light as lite",
"BLUEON = str(\"blue on\") BLUEOFF = str(\"blue off\") REDON =",
"GREENOFF = str(\"green off\") YELLOWON = str(\"yellow on\") YELLOWOFF =",
"= True response = \"\" if command.find(COMMAND1) >= 0: response",
"= \"testing testing\" COMMAND2 = \"roger roger\" BLUEON = str(\"blue",
"on\") BLUEOFF = str(\"blue off\") REDON = str(\"red on\") REDOFF",
"+ \"Turning :sunny: ON...\") elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False)",
"= str('light') def setup(): import RPi.GPIO as GPIO import slackbot_wems.chris.light",
"here COMMAND1 = \"testing testing\" COMMAND2 = \"roger roger\" BLUEON",
"handling code goes in this function def handle_command(command): \"\"\" Determine",
"# Green LED Commands elif command.find(GREENON) >= 0: GPIO.output(5, True)",
"7 Segment Commands elif command.find(CLOCK) >= 0: print('Updating the clock!')",
"lite import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup",
"\"Turning :sunny: ON...\") elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response",
"str(\"yellow off\") CLOCK = str(\"update clock\") SCRAMBLE = str('scramble the",
"0: GPIO.output(17, True) response = emoji.emojize(\"\" + \"Turning :radio_button: ON...\")",
"LED Commands elif command.find(YELLOWON) >= 0: GPIO.output(22, True) response =",
">= 0: GPIO.output(22, True) response = emoji.emojize(\"\" + \"Turning :sunny:",
"Blue LED Commands elif command.find(BLUEON) >= 0: GPIO.output(17, True) response",
"command.find(SINGLEREADING) >= 0: a = lite.printReading() a = int(a) time.sleep(1)",
"# Pin Setup GPIO.setup(17, GPIO.OUT) # BLUE LED GPIO.setup(27, GPIO.OUT)",
"elif command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up:",
"str(\"green off\") YELLOWON = str(\"yellow on\") YELLOWOFF = str(\"yellow off\")",
"Commands elif command.find(REDON) >= 0: GPIO.output(27, True) response = emoji.emojize(\"\"",
"str(\"update clock\") SCRAMBLE = str('scramble the 7') HACKER = str('hack",
"False) response = emoji.emojize(\"\" + \"Turning :sunny: OFF...\") # 7",
"Red LED Commands elif command.find(REDON) >= 0: GPIO.output(27, True) response",
"is what the LDR Sensor said to me: ' +",
":thumbs_up:')) # Blue LED Commands elif command.find(BLUEON) >= 0: GPIO.output(17,",
"SINGLEREADING = str('light') def setup(): import RPi.GPIO as GPIO import",
"command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:'))",
"print(emoji.emojize(\":egg: There is nothing better than scrambled eggs! :egg:\")) response",
"GPIO.output(17, False) response = emoji.emojize(\"\" + \"Turning :radio_button: OFF...\") #",
"as GPIO import slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7 as segment",
"emoji.emojize(\"\" + \"Turning :radio_button: ON...\") elif command.find(BLUEOFF) >= 0: GPIO.output(17,",
"0: GPIO.output(17, False) response = emoji.emojize(\"\" + \"Turning :radio_button: OFF...\")",
"= str(\"red on\") REDOFF = str(\"red off\") GREENON = str(\"green",
"LED GPIO.setup(27, GPIO.OUT) # RED LED GPIO.setup(5, GPIO.OUT) # GREEN",
"str(\"red off\") GREENON = str(\"green on\") GREENOFF = str(\"green off\")",
"testing\" COMMAND2 = \"roger roger\" BLUEON = str(\"blue on\") BLUEOFF",
"False) response = emoji.emojize(\"\" + \"Turning :radio_button: OFF...\") # Red",
"\"Turning :radio_button: OFF...\") # Red LED Commands elif command.find(REDON) >=",
"GPIO.output(5, False) response = emoji.emojize(\"\" + \"Turning :green_apple: OFF...\") #",
"YELLOW LED GPIO.setup(12, GPIO.OUT) # LDR setup = False #",
"elif command.find(REDON) >= 0: GPIO.output(27, True) response = emoji.emojize(\"\" +",
"+ \"Turning :sunny: OFF...\") # 7 Segment Commands elif command.find(CLOCK)",
"\"\"\" if not setup: setup_gpio() setup = True response =",
"GPIO.output(22, False) response = emoji.emojize(\"\" + \"Turning :sunny: OFF...\") #",
"= emoji.emojize(\"\" + \"Turning :red_circle: ON...\") elif command.find(REDOFF) >= 0:",
"= emoji.emojize(\"\" + \"Turning :sunny: ON...\") elif command.find(YELLOWOFF) >= 0:",
"emoji # Put your commands here COMMAND1 = \"testing testing\"",
"LED GPIO.setup(12, GPIO.OUT) # LDR setup = False # Your",
"ON...\") elif command.find(BLUEOFF) >= 0: GPIO.output(17, False) response = emoji.emojize(\"\"",
"emoji.emojize(\"\" + \"Turning :sunny: OFF...\") # 7 Segment Commands elif",
"on\") REDOFF = str(\"red off\") GREENON = str(\"green on\") GREENOFF",
"True) response = emoji.emojize(\"\" + \"Turning :sunny: ON...\") elif command.find(YELLOWOFF)",
"COMMAND2 = \"roger roger\" BLUEON = str(\"blue on\") BLUEOFF =",
"If so, take action and return a response, if necessary.",
"0: GPIO.output(5, True) response = emoji.emojize(\"\" + \"Turning :green_apple: ON...\")",
"= lite.printReading() a = int(a) time.sleep(1) print(a) response = ('Here",
"command.find(REDOFF) >= 0: GPIO.output(27, False) response = emoji.emojize(\"\" + \"Turning",
":sunny: ON...\") elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response =",
"lite.printReading() a = int(a) time.sleep(1) print(a) response = ('Here is",
"response = (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED",
"slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup GPIO.setup(17, GPIO.OUT)",
"response = emoji.emojize(\"\" + \"Turning :radio_button: OFF...\") # Red LED",
"0: print('Message') response = segment.hacker() elif command.find(SINGLEREADING) >= 0: a",
"clock\") SCRAMBLE = str('scramble the 7') HACKER = str('hack the",
"this function def handle_command(command): \"\"\" Determine if the command is",
"handle_command(command): \"\"\" Determine if the command is valid. If so,",
"if command.find(COMMAND1) >= 0: response = str(\"Surprise!\") elif command.find(COMMAND2) >=",
":red_circle: OFF...\") # Green LED Commands elif command.find(GREENON) >= 0:",
"= str(\"update clock\") SCRAMBLE = str('scramble the 7') HACKER =",
"\"Turning :red_circle: ON...\") elif command.find(REDOFF) >= 0: GPIO.output(27, False) response",
"OFF...\") # Yellow LED Commands elif command.find(YELLOWON) >= 0: GPIO.output(22,",
"setup_gpio() setup = True response = \"\" if command.find(COMMAND1) >=",
"response = str(\"Surprise!\") elif command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\\n",
"Commands elif command.find(CLOCK) >= 0: print('Updating the clock!') response =",
">= 0: print('Updating the clock!') response = segment.updateClock() elif command.find(SCRAMBLE)",
"response, if necessary. \"\"\" if not setup: setup_gpio() setup =",
"print('Updating the clock!') response = segment.updateClock() elif command.find(SCRAMBLE) >= 0:",
"return a response, if necessary. \"\"\" if not setup: setup_gpio()",
"slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #",
"BLUE LED GPIO.setup(27, GPIO.OUT) # RED LED GPIO.setup(5, GPIO.OUT) #",
"elif command.find(YELLOWOFF) >= 0: GPIO.output(22, False) response = emoji.emojize(\"\" +",
"0: GPIO.output(22, True) response = emoji.emojize(\"\" + \"Turning :sunny: ON...\")",
"not setup: setup_gpio() setup = True response = \"\" if",
"command.find(BLUEOFF) >= 0: GPIO.output(17, False) response = emoji.emojize(\"\" + \"Turning",
"= str(\"blue on\") BLUEOFF = str(\"blue off\") REDON = str(\"red",
"False # Your handling code goes in this function def",
"There is nothing better than scrambled eggs! :egg:\")) response =",
"nothing better than scrambled eggs! :egg:\")) response = segment.scramble() elif",
"elif command.find(CLOCK) >= 0: print('Updating the clock!') response = segment.updateClock()",
"setup(): import RPi.GPIO as GPIO import slackbot_wems.chris.light as lite import",
"# Your handling code goes in this function def handle_command(command):",
"+ \"Turning :red_circle: OFF...\") # Green LED Commands elif command.find(GREENON)",
"= str(\"yellow on\") YELLOWOFF = str(\"yellow off\") CLOCK = str(\"update",
"True) response = emoji.emojize(\"\" + \"Turning :green_apple: ON...\") elif command.find(GREENOFF)",
"<reponame>wray/wems<filename>slackbot_wems/chris/slacklib.py<gh_stars>1-10 import time import emoji # Put your commands here",
"response = emoji.emojize(\"\" + \"Turning :sunny: ON...\") elif command.find(YELLOWOFF) >=",
"# Red LED Commands elif command.find(REDON) >= 0: GPIO.output(27, True)",
"the LDR Sensor said to me: ' + str(a)) return",
"segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup GPIO.setup(17, GPIO.OUT) # BLUE",
"= str('scramble the 7') HACKER = str('hack the 7') SINGLEREADING",
"response = segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There is",
"str(\"blue off\") REDON = str(\"red on\") REDOFF = str(\"red off\")",
">= 0: response = str(\"Surprise!\") elif command.find(COMMAND2) >= 0: response",
"+ \"Turning :green_apple: ON...\") elif command.find(GREENOFF) >= 0: GPIO.output(5, False)",
"necessary. \"\"\" if not setup: setup_gpio() setup = True response",
"on\") GREENOFF = str(\"green off\") YELLOWON = str(\"yellow on\") YELLOWOFF",
"response = emoji.emojize(\"\" + \"Turning :red_circle: ON...\") elif command.find(REDOFF) >=",
"goes in this function def handle_command(command): \"\"\" Determine if the",
"as lite import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin",
">= 0: print('Message') response = segment.hacker() elif command.find(SINGLEREADING) >= 0:",
"# Yellow LED Commands elif command.find(YELLOWON) >= 0: GPIO.output(22, True)",
"YELLOWOFF = str(\"yellow off\") CLOCK = str(\"update clock\") SCRAMBLE =",
"LDR Sensor said to me: ' + str(a)) return response",
"emoji.emojize(\"\" + \"Turning :red_circle: ON...\") elif command.find(REDOFF) >= 0: GPIO.output(27,",
"command.find(COMMAND1) >= 0: response = str(\"Surprise!\") elif command.find(COMMAND2) >= 0:",
"0: print(emoji.emojize(\":egg: There is nothing better than scrambled eggs! :egg:\"))",
"COMMAND1 = \"testing testing\" COMMAND2 = \"roger roger\" BLUEON =",
"7') HACKER = str('hack the 7') SINGLEREADING = str('light') def",
"LDR setup = False # Your handling code goes in",
"setup: setup_gpio() setup = True response = \"\" if command.find(COMMAND1)",
"emoji.emojize(\"\" + \"Turning :red_circle: OFF...\") # Green LED Commands elif",
"(emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED Commands elif",
":sunny: OFF...\") # 7 Segment Commands elif command.find(CLOCK) >= 0:",
"RED LED GPIO.setup(5, GPIO.OUT) # GREEN LED GPIO.setup(22, GPIO.OUT) #",
"off\") YELLOWON = str(\"yellow on\") YELLOWOFF = str(\"yellow off\") CLOCK",
">= 0: GPIO.output(5, False) response = emoji.emojize(\"\" + \"Turning :green_apple:",
"response = emoji.emojize(\"\" + \"Turning :green_apple: ON...\") elif command.find(GREENOFF) >=",
"= str(\"Surprise!\") elif command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\\n is\\n",
"GPIO.setup(17, GPIO.OUT) # BLUE LED GPIO.setup(27, GPIO.OUT) # RED LED",
"7') SINGLEREADING = str('light') def setup(): import RPi.GPIO as GPIO",
"segment.hacker() elif command.find(SINGLEREADING) >= 0: a = lite.printReading() a =",
"GPIO.setup(22, GPIO.OUT) # YELLOW LED GPIO.setup(12, GPIO.OUT) # LDR setup",
"GPIO.output(5, True) response = emoji.emojize(\"\" + \"Turning :green_apple: ON...\") elif",
"GPIO.OUT) # BLUE LED GPIO.setup(27, GPIO.OUT) # RED LED GPIO.setup(5,",
"True) response = emoji.emojize(\"\" + \"Turning :radio_button: ON...\") elif command.find(BLUEOFF)",
"= int(a) time.sleep(1) print(a) response = ('Here is what the",
"import emoji # Put your commands here COMMAND1 = \"testing",
"GPIO.setup(12, GPIO.OUT) # LDR setup = False # Your handling",
"= \"\" if command.find(COMMAND1) >= 0: response = str(\"Surprise!\") elif",
"on\") YELLOWOFF = str(\"yellow off\") CLOCK = str(\"update clock\") SCRAMBLE",
"if the command is valid. If so, take action and",
"GPIO.output(17, True) response = emoji.emojize(\"\" + \"Turning :radio_button: ON...\") elif",
"GREEN LED GPIO.setup(22, GPIO.OUT) # YELLOW LED GPIO.setup(12, GPIO.OUT) #",
"GPIO.OUT) # LDR setup = False # Your handling code",
"= (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue LED Commands",
"False) response = emoji.emojize(\"\" + \"Turning :red_circle: OFF...\") # Green",
"GREENON = str(\"green on\") GREENOFF = str(\"green off\") YELLOWON =",
"the command is valid. If so, take action and return",
"emoji.emojize(\"\" + \"Turning :green_apple: ON...\") elif command.find(GREENOFF) >= 0: GPIO.output(5,",
"GPIO.setup(27, GPIO.OUT) # RED LED GPIO.setup(5, GPIO.OUT) # GREEN LED",
"0: response = (emoji.emojize('Python\\n is\\n :thumbs_up: :thumbs_up: :thumbs_up:')) # Blue",
":thumbs_up: :thumbs_up:')) # Blue LED Commands elif command.find(BLUEON) >= 0:",
"HACKER = str('hack the 7') SINGLEREADING = str('light') def setup():",
"REDON = str(\"red on\") REDOFF = str(\"red off\") GREENON =",
"BLUEOFF = str(\"blue off\") REDON = str(\"red on\") REDOFF =",
"time import emoji # Put your commands here COMMAND1 =",
"command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg: There is nothing better than scrambled",
">= 0: GPIO.output(5, True) response = emoji.emojize(\"\" + \"Turning :green_apple:",
"GPIO.OUT) # GREEN LED GPIO.setup(22, GPIO.OUT) # YELLOW LED GPIO.setup(12,",
"= emoji.emojize(\"\" + \"Turning :green_apple: ON...\") elif command.find(GREENOFF) >= 0:",
"off\") REDON = str(\"red on\") REDOFF = str(\"red off\") GREENON",
"CLOCK = str(\"update clock\") SCRAMBLE = str('scramble the 7') HACKER",
"import slackbot_wems.chris.segment7 as segment GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) # Pin Setup GPIO.setup(17,",
"# 7 Segment Commands elif command.find(CLOCK) >= 0: print('Updating the",
">= 0: print(emoji.emojize(\":egg: There is nothing better than scrambled eggs!",
"Put your commands here COMMAND1 = \"testing testing\" COMMAND2 =",
">= 0: a = lite.printReading() a = int(a) time.sleep(1) print(a)",
"a = int(a) time.sleep(1) print(a) response = ('Here is what",
"str(\"Surprise!\") elif command.find(COMMAND2) >= 0: response = (emoji.emojize('Python\\n is\\n :thumbs_up:",
"0: response = str(\"Surprise!\") elif command.find(COMMAND2) >= 0: response =",
"response = segment.hacker() elif command.find(SINGLEREADING) >= 0: a = lite.printReading()",
"in this function def handle_command(command): \"\"\" Determine if the command",
"elif command.find(BLUEOFF) >= 0: GPIO.output(17, False) response = emoji.emojize(\"\" +",
"response = emoji.emojize(\"\" + \"Turning :radio_button: ON...\") elif command.find(BLUEOFF) >=",
"OFF...\") # 7 Segment Commands elif command.find(CLOCK) >= 0: print('Updating",
">= 0: GPIO.output(27, False) response = emoji.emojize(\"\" + \"Turning :red_circle:",
"+ \"Turning :red_circle: ON...\") elif command.find(REDOFF) >= 0: GPIO.output(27, False)",
"str('scramble the 7') HACKER = str('hack the 7') SINGLEREADING =",
"GPIO.OUT) # RED LED GPIO.setup(5, GPIO.OUT) # GREEN LED GPIO.setup(22,",
"GPIO.output(27, False) response = emoji.emojize(\"\" + \"Turning :red_circle: OFF...\") #",
"0: GPIO.output(22, False) response = emoji.emojize(\"\" + \"Turning :sunny: OFF...\")",
"a response, if necessary. \"\"\" if not setup: setup_gpio() setup",
"the 7') HACKER = str('hack the 7') SINGLEREADING = str('light')",
"GPIO.output(22, True) response = emoji.emojize(\"\" + \"Turning :sunny: ON...\") elif",
":green_apple: OFF...\") # Yellow LED Commands elif command.find(YELLOWON) >= 0:",
"import RPi.GPIO as GPIO import slackbot_wems.chris.light as lite import slackbot_wems.chris.segment7",
"if not setup: setup_gpio() setup = True response = \"\"",
"Yellow LED Commands elif command.find(YELLOWON) >= 0: GPIO.output(22, True) response",
">= 0: GPIO.output(22, False) response = emoji.emojize(\"\" + \"Turning :sunny:",
"\"Turning :green_apple: ON...\") elif command.find(GREENOFF) >= 0: GPIO.output(5, False) response",
"function def handle_command(command): \"\"\" Determine if the command is valid.",
"= segment.scramble() elif command.find(HACKER) >= 0: print('Message') response = segment.hacker()",
"is valid. If so, take action and return a response,",
"def handle_command(command): \"\"\" Determine if the command is valid. If",
"+ \"Turning :radio_button: OFF...\") # Red LED Commands elif command.find(REDON)",
"response = emoji.emojize(\"\" + \"Turning :sunny: OFF...\") # 7 Segment",
"valid. If so, take action and return a response, if",
"# LDR setup = False # Your handling code goes",
"= ('Here is what the LDR Sensor said to me:",
"off\") GREENON = str(\"green on\") GREENOFF = str(\"green off\") YELLOWON",
"the clock!') response = segment.updateClock() elif command.find(SCRAMBLE) >= 0: print(emoji.emojize(\":egg:",
"= emoji.emojize(\"\" + \"Turning :radio_button: ON...\") elif command.find(BLUEOFF) >= 0:",
"int(a) time.sleep(1) print(a) response = ('Here is what the LDR",
"= str(\"green off\") YELLOWON = str(\"yellow on\") YELLOWOFF = str(\"yellow"
] |